tags:

views:

191

answers:

7

We know that no matter whether an exception is thrown, or caught and handled it, the finally block will get executed, So i was curious that is there any possibility that finally block will not executed.

And if System.exit() is called either in try or catch, then also will the finally gets called?

+2  A: 

In the Java documentation:

http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html

It explains Finally very well.

They do note that if the JVM exits, that the finally block will not be called. Or if a thread that is running the block of code gets killed, the finally block will not be called. In all other cases it will.

MarkPowell
+14  A: 

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Source: java.sun.com: Java Tutorial: The finally Block

Daniel Vassallo
take note of the "may" word there.
Joset
+1  A: 

One thing I can think of right now is an OutOfMemoryError in which case there is a chance that no further code in your app can be executed.

neutrino
Even in case of an OutOfMemoryError, the finally block will be executed. The execution of the finally block itself may then of course cause an OutOfMemoryError itself, but that may also happen, even if the try block completed succesfully.
jarnbjo
+4  A: 

System.exit() will prevent a finally block from executing.

msw
A: 

If some Java Native Interface method segfaults (a library function outside of java but called from there crashes) a finally method will also not be called because the entire JVM stops.

Errors in the JVM itself also result in a crash and prevent everything from continued execution.

extraneon
+1  A: 

System.exit(1); you can use

giri
+1  A: 
try {
    System.out.println("BEFORE");
    System.exit(0);
    System.out.println("AFTER");
} finally {
    System.out.println("FINALLY");
}

this will give you the output:

BEFORE
Joset