What is the difference between
try {
// action A
}
catch(Exception e) {
// action B
}
finally {
// action C
}
and
try {
// action A
}
catch(Exception e) {
// action B
}
// action C
I have read that you can return from inside a catch block and still have the finally block execute. Are there any other differences?
Things that happen within the finally block are guaranteed to occur no matter what happens in the try-catch-block. If an exception happens that is not encapsulated by Exception (e.g., extends Throwable, such as various Errors), then it still runs the finally block.
One thing to be aware of: if, within the finally block, a RuntimeException is thrown, or another Exception escapes from within it, then the rest of the finally block will not execute. Also, as Lord Torgamus pointed out, it is contingent on the JVM running. In addition, and probably obviously, it is also contingent on the thread not being stopped.
Most of the existing answers contain pieces of the right answer, but none are quite spot-on.
The finally block is always guaranteed to be reached after the try and potentially catch blocks if the JVM does not shut down beforehand. However, if a bit of code inside the finally block shuts down the JVM, or throws an exception its own, the end of the block might not be reached.
Per the Sun Certified Programmer for Java 6 Study Guide:
The only exception to the
finally-will-always-be-called rule is that afinallywill not be invoked if the JVM shuts down.Just because
finallyis invoked does not mean it will complete.
The final word is, as always, the Java Language Specification. The behavior of finally is explained exhaustively in §14.20.2 Execution of try-catch-finally.
As an extra note: you're right that a return in the try won't stop finally from running. In fact, finally is entered immediately after the return is encountered, before it executes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With