I'm trying to catch an "android.database.sqlite.SQLiteException: error code 5: database is locked" exception with:
try {
db.insert("mytable", null, myvalues);
} catch(SQLiteException e) {
Log.d("My App", "caught");
...
}
For some reason, I still get the error, and "caught" doesn't show up in LogCat. I tried catching a general "exception", but that still doesn't work. What's wrong?
UPDATE
I found the issue, and it is really weird: for some reason changing db.insert() to db.insertOrThrow() as goto10 stated magically fixed everything. The error was comming from that line, but maybe it wasn't throwing an exception and only crashing or something?
I don't believe that .insert will throw an exception. You're probably just seeing a log message that's being written by it when it catches the exception internally. If you want it to throw an exception when an insert fails, use .insertOrThrow instead.
Try this
try {
} catch( SQLiteException e) {
Log.e("My App",e.toString(), e);
}
If that catch block is failing to catch the exception then either it isn't being thrown inside that particular try block, or you've got the wrong exception. The fact that it still doesn't work if you catch Exception says that it is the former problem.
So you need to find out where the exception is really being throw. I'd try changing the logging configurations to get LogCat to log full exception stacktrace. That should tell you where it was thrown. If you can't do that, then you'll need to find this using a debugger ... or by trawling through your applications source code to find where the exception is being logged.
(The other possibility is that the catch block is catching the exception, but you've got your logging configs set up to discard "debug" log events.)
The exception is probably thrown when you open the database, not when you insert a new row.
Related
I have the following Java code (that I thought was OK) but the IDE is warning me that "IOExcpetion e is immediately rethrown."
I'm new to exception handling in Java, and I wasn't aware there was anything wrong with doing that.
From what I'm reading, it looks like my other options is to simply delete the catch block and replace it with a finally block... but then it warns that the finally block is empty.
I don't have any ideas on what I should do differently.
private InputStream getFlutterAssetAsInputStream(String fromAsset) throws IOException {
String assetPath = binding
.getFlutterAssets()
.getAssetFilePathBySubpath(fromAsset, PACKAGE_NAME);
try {
return binding.getApplicationContext().getAssets().open(assetPath);
} catch (IOException e) {
throw e;
}
}
This
try {
return binding.getApplicationContext().getAssets().open(assetPath);
}
catch (IOException e) {
throw e;
}
is functionally equivalent to this:
return binding.getApplicationContext().getAssets().open(assetPath);
Your IDE is telling you that your try-catch is pointless. It does nothing.
So what do you want to do?
Pass the exception on to your caller? In which case get rid of the try-catch
Signal a different exception on to the caller - maybe one with a more appropriate error message for the specific circumstances? Then make and throw a new exception object with a better error message.
Do something to handle the situation - at the very least, maybe display an error message? Log the event to enable debugging? Then write code in the catch-block to do that. And then you have to decide what happens next.
Fundamentally, this is a design issue. IO errors happen. So how does this method that you're writing want to handle IO errors?
In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.
I am quite new to Java and stumbled upon an problem, I can't understand (I am using Eclipse Luna for developing and executing):
I call a method that might throw an error and surrounded it with a try-catch-block:
try {
transaction.execute();
} catch (ModbusIOException e) {
log.debug("Fehler bei Modbustransaction: ModbusIOException - " + e.getMessage());
e.printStackTrace();
} ... // more catches
The execute-method actually throws the ModbusIOException - but it is not caught in the catch-block. In the console I got the following output:
net.wimpi.modbus.ModbusIOException: Read failed
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:180)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at de.vksys.modbusclient.ModbusClient.getPlantState(ModbusClient.java:121)
at de.vksys.modbusclient.ReconnectingModbusClient.main(ReconnectingModbusClient.java:36)
If I click at the line with getPlantState Eclipse marks the line in the try-block above. But why isn't it caught there? I also checked the full name of the ModbusIOException in the catch block and is the same ... net.wimpi.modbus.ModbusIOException.
Any idea, what might be the reason? If you need more code to track this down, just tell me.
Thanks in advance,
Frank
It indeed caught the exception. You just printed the stack trace and that's what you see in the standard output.
Catching an exception, doesn't mean that it wont maintain the stack trace and handling exception means that you need to code it so you could recover from the exception (which is what has happened in your case else your program would have went to the parent method which called your method rolling back the stack i.e. in readResponse method) where you might say ok things happen or you rethrow the exception. for e.g. given a code as below:
void myMethod() {
try {
methodThatThrowsIOException();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("I will be printed");
If you didn't caught the exception, then you would never have executed print statement like "I will be printed"
}
I've come across some really strange behaviour in my Java code. There is a exception shown on my Eclipse log console saying Exception:java.lang.NullPointerException with no reference to the code where it occurred.
On debugging I found out a line where this occurred and so put it in try-catch hoping I catch it. However it didn't return in catch block.
The strange part being even though there's exception thrown at the line immediately after it executes and the execution continues normally.
Can some one please tell me the probable cause?
I could have attached the source code but I have checked the parameters and all seem fine.
My main reason for this post is to learn about such behavior if any of you coders ever came across.
Probably a problem with Eclipse. I have seen that behaviour before, and restarting Eclipse solved the problem.
Please check whether your builder is activated and the changed source code is build automatically. Otherwise your code changes will never get it into your runtime application.
I am pretty sure, that the executed source code is different to the source code shown in your editor.
If you see the exception's message but no stack trace, that is caused by code that looks like this:
try
{
// something which causes the exception
}
catch (final Exception err)
{
System.out.println(err);
}
The problem with this code is that it only prints the result of the exception's .toString() method. For most exceptions this is just the exception class and the message. This code omits the stack trace, thus making it much harder to debug the problem.
If the exception is to be caught, then change the code to look like this for the stack trace to be included in the output:
try
{
// something which causes the exception
}
catch (final Exception err)
{
err.printStackTrace();
}
The goal is to be able to do:
throw new RuntimeException();
without it printing:
Exception in thread "main" java.util.RuntimeException
at grame.GrameManager.add(GrameManager.java:40)
at grame.GrameManager.add(GrameManager.java:47)
at grame.Entity.<init>(Entity.java:56)
at grame.Entity.<init>(Entity.java:28)
at test.Test.main(Test.java:20)
(for example).
Is this possible? If so, how would I go about doing this?
Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.
If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).
You can redirect System.err by setting System.setErr(null);
No thrown exception ever directly generates a stacktrace to the error console. It's up to the code who is calling it to do so. In the case of a main program:
public static void main(String args[]) throws Exception {
// do something that throws an exception
}
If you don't catch the exception, the system will actually spit it out to the console i believe.
Somewhere along the way, you need to deal with the exception. If showing it in the GUI is what you want, then you'll have to do something like this:
public interface ExceptionHandler {
void handleException(Exception e);
}
public static void main(String args[]) {
ExceptionHandler exceptionHandler = ...;
try {
// something that might throw an exception
}
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Just catch the exception, and don't put anything in the catch block.
I should add that doing this is generally a bad idea. Having that stack trace, or some sort of message is very useful when finding out what went wrong in your program.
If you want the method to kill the program without printing a stack trace, place it in a try/catch block, and under catch simply use the statement:
System.exit(1)
This lets the system know that the program exited with an irregular (non-zero) state, but does not print anything to System.err.
All that you really need to do is catch it... However, this is a really bad idea. You may want to make your own exception and catch that. This way you will not swallow exceptions that you should not be ignoring. The only time that you should really consider to do this, is if you cannot allow your application to blow up. If that is the case then you should at the very least log the error.
This explains it better than I can (and is a good resource regardless). Basically, it suggests that:
"If a client can reasonably be expected to recover from an exception,
make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Like this:
try {
some code...
} catch (RuntimeException e) {
}
1. Java compiler only cares during compilation that you have given a catch for a try, whether you implement any code in the catch or not.
2. You can keep the catch block empty, or print it on the console, log it..etc....
eg:
try{
}catch(Exception ex){
}
3. But printStackTrace() prints the method name, class name , file name and the line number where the exception has occurred.