13

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?

chance
  • 6,307
  • 13
  • 46
  • 70
  • FYI, on the system I have handy, which has Sun/Oracle's Java6 on it (specifically, "Java(TM) SE Runtime Environment (build 1.6.0_26-b03)"), I never see an exception message. I only see the "finally" line. Whereas if I remove the `System.exit(0)` line, I see both (with the "finally" first, reliably). – T.J. Crowder Nov 24 '11 at 10:17

5 Answers5

16

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?

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 3
    Not "maybe". This is the reason you're seeing this. An uncaught exception will get printed to the error stream. The reason the order is not defined is because it will be your console that depends which buffer gets flushed first. – Joeri Hendrickx Nov 24 '11 at 10:17
  • 2
    Ok, if I print "finally" to System.err, it seems that it comes always before stacktrace. – chance Nov 24 '11 at 10:19
7

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 "

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
3

Finally block is executed always. It is guaranteed by the language. It is executed if you try block is terminated successfully or if any exception is thrown.

There are checked and unchecked exceptions. For unchecked exceptions (Runtime and Errors) you do not have to write catch block. But all exceptions are caught by JVM that prints the stacktrace. When your finally block terminates application it does not have the chance to print the stacktrace, so you do not see it.

Generally exiting program in finally block is bad because it will exit even if your code runs successfully. And more generally finally block is typically needed for cleanup like closing files, sockets etc and not for more complicated business logic.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • 1
    I call System.exit() only for getting a return code from my Java application. Otherwise what is the return code if the application is interrupted by RuntimeException? – chance Nov 24 '11 at 10:47
1

there are two blocks that we can use with try those are catch and finally.

catch block is executed when any RunTime exception is thrown (before finally) and finally block is executed in the end, irrespective of exception is thrown or not.

so if you want to do something on exception being thrown then you can put that in catch(Excepion e) block.

And what are you seeing is the duty of JVM to perform what ever is written in the finally block before terminating the program execution.

And when program is terminated it by default shows you the trace of the exception thrown.

gprathour
  • 14,813
  • 5
  • 66
  • 90
0

Finally method always will be executed even in case of return statement in try block ,but in some cases where throwing Errors(Run time memory) in try block there is no guarantee finally block executed completely.

In your case finally block always executed and exception throws by main method from the JVM since you are not handle the exception.

  • Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) and follow the guideline there to provide quality answer. – thewaywewere Jun 21 '17 at 13:41