I have a thread in which I catch all errors in a big, all-encompassing catch block. I do this so that I can report any error, not just expected ones, in my application. My Runnable looks like this:
public final void run()
{
try
{
System.out.println("Do things"); /* [1] */
doUnsafeThings();
}
catch (Throwable t)
{
System.out.println("Catch"); /* [2] */
recover();
}
finally
{
System.out.println("Finally"); /* [3] */
}
}
I would expect the NPE to be caught by the Throwable catch block. Instead, the output at [2] is not printed, and neither is [3]. The output at [1] is printed.
What I do get on the console, is this:
Uncaught exception java/lang/NullPointerException.
What on earth is going on here?
For the court records, I'm using J2ME, and this is running in Sun's WTK v2.5.2 emulator.
I'm tempted to put it down to JVM implementation dodginess but I can't help feeling that I'm just missing something.
To clarify for the avoidance of doubt (Since the example code is obviously altered from my production code)
- There is nothing outside of the try/catch/finally block in the run method.
- There is a System.out.println at the start of each of those blocks - What follows those console statements should not matter.
As you mention you are using a
Runnable
- does this by any chance mean that you are using multiple threads as well? If thedoUnsafeThings()
method internally spawns a different thread again and that produces the exception, you might not get it in the thread your catch block is. See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.UncaughtExceptionHandler.htmlIt is generally a bad practice to catch NullPointerException.
Programmers typically catch NullPointerException under three circumstances:
Of these three circumstances, only the last is acceptable. following this link:
Catch NullPointerException
Is it possible that the thread is being killed by some other code? In general a finally block always executes unless the thread is abnormally terminated, either by System.exit() or something similar.
just add some logging in the doUnsafeThings(); to see if that method is doing what you expect (e.g put a try catch finally and log something)
When I looked at your code it seems that recover() is throwing an exception, so the advice given by Jon would be excellent to follow.
If you gave us a stack trace you may get better help.
When I try to catch exceptions I do something like this:
I don't like to nest exceptions, but I don't like my catch block throwing exceptions.
Sounds like you'll need some trial and error. May I suggest:
By having an explicit catch for NullPointerException, it should become obvious if the exception is from within the try block or a catch/finally block.