Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between finally and no finally?

Tags:

java

finally

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?

like image 263
Sidor Avatar asked Apr 29 '11 15:04

Sidor


2 Answers

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.

like image 65
pickypg Avatar answered Sep 22 '22 12:09

pickypg


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 a finally will not be invoked if the JVM shuts down.

  • Just because finally is 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.

like image 44
Pops Avatar answered Sep 25 '22 12:09

Pops