Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 525
izb Avatar asked Dec 01 '22 12:12

izb


2 Answers

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.

like image 198
izb Avatar answered Dec 04 '22 10:12

izb


Sounds like you'll need some trial and error. May I suggest:

try {
    doEvilStuff();
} catch (NullPointerException ex) { 
    System.out.println("NPE encountered in body"); 
} catch (Throwable ex) {
    System.out.println("Regular Throwable: " + ex.getMessage());
} finally {
    etc...
}

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.

like image 22
Mike Avatar answered Dec 04 '22 11:12

Mike