Why is my NullPointerException not being caught in my catch block?

izb picture izb · Apr 22, 2009 · Viewed 16.5k times · Source

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.

Answer

izb picture izb · Apr 22, 2009

The answer turns out that I'm an idiot. I'd explain what went wrong, but let's just call it "one of those bugs".

I had momentarily forgotten that the thread that ran the runnable was a custom thread class (To get round some Nokia bugs). It called run() repeatedly between calls to a canWait() method.

The canWait method was responsible for the failure, and run wasn't failing at all. To top it off, I have console-blindness and completely but accidentally misquoted the sequence of events in my question.