3

The given java code is not going to the finally block, I thought these blocks were supposed to execute no matter what:

public static void main(String[] args) {
    try {
        System.out.println("Hello world");
        System.exit(0);
    } finally {
        System.out.println("Goodbye world");
    }
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
newUser
  • 53
  • 3

5 Answers5

5
System.exit(0);

will unload the JVM i.e no further java instructions are processed That is the reason for not being exicuting the finally{}

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57
4

Yes, that's normal. The finally blocks is always executed, except in the case where the JVM is stopped before reaching the end of the code, which is your case here, as you exit the JVM.

Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
4

As stated in the Java 6 System.exit() docs:

The call System.exit(n) is effectively equivalent to the call: Runtime.getRuntime().exit(n)

And, if you go and look at Runtime.exit() (my bold):

Terminates the currently running Java virtual machine by initiating its shutdown sequence. This method never returns normally.

The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts.

Basically, the only one this function can return (and hence allow the finally clause to run) is for it to raise a SecurityException because whatever security manager is running disallows exiting with the given code.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

The System.exit method stops the execution of the current thread and all others threads. The presence of a finally does not give a thread special permission to continue executing.

A previous discusses this in great detail. How does Java's System.exit() work with try/catch/finally blocks?

Community
  • 1
  • 1
AurA
  • 12,135
  • 7
  • 46
  • 63
0

By System.exit(0) You are exiting from Jvm so no lines after this will get executed and That's why you are finding your finally block as unexecuted.

Abhishek_Mishra
  • 4,551
  • 4
  • 25
  • 38