The code does not reach the "final" block

Given java code does not fit a block finally

, I thought these blocks should have been executed no matter what:

public static void main(String[] args) {
    try {
        System.out.println("Hello world");
        System.exit(0);
    } finally {
        System.out.println("Goodbye world");
    }
}

      

+3


source to share


5 answers


As stated in the Java 6 System.exit()

docs
:

Calling is System.exit(n)

actually equivalent to calling:Runtime.getRuntime().exit(n)

And if you go and see Runtime.exit()

(my bold):



Shuts down the current Java Virtual Machine by initiating its shutdown sequence. This method never returns normally.

The shutdown sequence for a virtual machine consists of two phases. In the first step, all registered stop hooks, if any, are triggered in a specific unspecified order and are allowed to start simultaneously until they finish. At the second stage, all uninitiated finalizers are run if the finalize on exit option is enabled. After that, the virtual machine stops.

Basically, the only function that this function can return (and therefore allow execution finally

) is that it raises SecurityException

, because any security manager works with a denied exit with a given code.

+4


source


System.exit(0);

      



will unload the JVM ie no further java instructions will be processed This is the reason for not setting finally{}

+5


source


Yes, it is normal. Blocks are finally

always executed, except when the JVM stops before reaching the end of the code, which is your case here when you exit the JVM.

+4


source


The method System.exit

stops the execution of the current thread and all other threads. Presence finally does not give the thread special permission to continue running.

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

+2


source


From System.exit(0)

you exit the Jvm, so no lines after that will get executed and that you will find your finally block as unexecuted.

0


source







All Articles