Why doesn't my NullPointerException fall into my catch block?

I have a thread in which I catch all the errors in a large, comprehensive catch block. I do this so that I can report any errors, not just expected, 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 NPE to catch the Throwable catch block. Instead, the conclusion in [2] is not printed, and not one of them [3]. The conclusion is deduced in [1].

What I do on the console is this:

Uncaught exception java/lang/NullPointerException.

What's going on here?

For court records, I use J2ME, and this works in the Sun WTK v2.5.2 emulator.

I am tempted to put it on a fine-tuning of the JVM implementation, but I cannot help but feel that I just missed something.

To clarify for the avoidance of doubt (as the sample code is obviously modified from my production code)

  • try/catch/finally.
  • System.out.println. , .
+3
9

, . , , " ".

, , runnable, ( Nokia). run() canWait().

canWait , . , , .

+6

, . :

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

catch NullPointerException, , try catch/finally.

+5

, ... .

, , , catch (, ,) - , -, , try. , , catch, finally .

, ...

EDIT: , System.out.println, - , ? :

catch (Throwable t) {
    // Will go bang if t.getCause() returns null
    System.out.println(t.getCause().getMessage());
}

System.out.println("Constant"), .

(, try), try ?

+4

, , recover() , , , , .

, .

, - :

try {
  doSomethingBad();
} catch(Exception e) {
   try {
      LogException(...);
   } catch(Exception e) {}       
} finally {
}

, , .

+2

, NullPointerException.

NullPointerException :

The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.
The program explicitly throws a NullPointerException to signal an error condition.
The code is part of a test harness that supplies unexpected input to the classes under test. 

. :

Catch NullPointerException

+1

, - ? finally , , System.exit(), - .

0
source
  • Are you sure you are looking for the right place in the code? Ie, is this the doUnsafeThings () block that you protect in the stack trace?

  • Perhaps there is a problem with your build method and you are debugging an old version of the code?

0
source

just add some entries to doUnsafeThings (); to make sure this method does what you expect (for example, try to catch the ending and register something)

0
source

Source: https://habr.com/ru/post/1706886/


All Articles