Java: try + finally
A finally block is always executed after the code in the preceeding try block. It doesn't matter if the try block throws an exception, whether or not the exception is caught, or if it executes a return statement. (The only way to prevent a finally block from running is by terminating the VM through System.exit or killing it manually.)
It's often used to restore some state after an operation, such as freeing up resources.
Without catch, no exception thrown
Without catch, exception thrown
Exception is thrown, finally block is executed, exception propagates:
With catch, no exception thrown
With catch, exception thrown
With return statement in try block
The return statement is executed, finally block runs, method actually returns.
With return in both try and finally blocks
In the snippet below, return 0 is executed, then the finally block kicks in and return 1 is executed. The second return overrides the first return which means that the 0 return value is discarded, and the method returns 1.
With throw in both try and finally block
The try block throws SomeException, the finally block kicks in and throws SomeOtherException. The second throw "wins" and the first exception is discarded.
Similarly a return in a finally block will cause an exception thrown from a try block to be discarded and throw in a finally block will cause a normal return value from a try block to be discarded.
Comments (3)
Excellent article
by Emiliano |
+1 very good visualization
Thanks a lot. In my opinion, it couldn't be explained better.
by Luis Iglesias |