Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught RuntimeException and finally clause: which comes first?

A RuntimeException is thrown in try block without being caught, while the finally clause invokes System.exit().

public static void main(String[] args) {
    try {
        Integer.valueOf("NotANumber");
    } finally {
        System.out.println("finally");
        System.exit(0);
    }
}

The output is

finally

If System.exit(0) is removed from finally, then the output is

finally
Exception in thread "main" java.lang.NumberFormatException: For input string: "NotANumber"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:449)
    at java.lang.Integer.valueOf(Integer.java:554)
    at exception.MyExcepTest.main(MyExcepTest.java:20)

Where "finally" may appears before, after or in between the meesage of NumberFormatException.

Can anybody explain it?

like image 809
chance Avatar asked Nov 24 '11 10:11

chance


2 Answers

The finally block will definitely be executed before the main method exits, and the stacktrace is printed by the JVM after that.

Maybe the stacktrace gets printed to System.err, and the two streams get mixed up in your console output in unpredictable ways (since they are produced basically simultaneously).

What happens when you print "finally" to System.err as well?

like image 171
Thilo Avatar answered Sep 20 '22 16:09

Thilo


The thing is, when there is an exception thrown.. The JVM 1st execute code with inside finally block and then throw the exception if catched or it will throw the exception and terminate the thread. so here when System.exit(0) is present in the finally block it terminate the thread immediately so the JVM doesnt get chance to throw the exception. so the out put is just the "finally "

like image 38
dku.rajkumar Avatar answered Sep 21 '22 16:09

dku.rajkumar