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

try { statement statement statement } finally { statement statement statement } statement statement statement

Without catch, exception thrown

Exception is thrown, finally block is executed, exception propagates:

try { statement statement throw new SomeException(); statement statement } finally { statement statement statement } statement statement statement

With catch, no exception thrown

try { statement statement statement } catch (SomeException e) { statement statement statement } finally { statement statement statement } statement statement statement

With catch, exception thrown

try { statement statement statement throw new SomeException(); statement statement statement } catch (SomeException e) { statement statement statement } finally { statement statement statement } statement statement statement

With return statement in try block

The return statement is executed, finally block runs, method actually returns.

try { statement statement return; statement statement } finally { statement statement statement } statement statement

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.

try { statement statement return 0; statement statement } finally { statement statement return 1; statement statement } statement statement

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.

try { statement statement throw new SomeException(); statement statement } finally { statement statement throw new SomeOtherException(); statement statement } statement statement

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.

Disclaimer: The examples above are for educational purposes only. Some of them will not compile due to unreachable code.

Comments