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

statement try { } finally { }

Without catch, exception thrown

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

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

With catch, no exception thrown

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

With catch, exception thrown

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

With return statement in try block

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

try { return; } finally { }

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 { return 0; } finally { return 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.

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

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.

Note: The examples are notional and only meant to illustrate the semantics. Some of them wouldn't actually compile due to unreachable code.

Comments (3)

User avatar

Thanks a lot. In my opinion, it couldn't be explained better.

by Luis Iglesias |  Reply
User avatar

Excellent article

by Emiliano |  Reply
User avatar

+1 very good visualization

by Valentin Kovalenko |  Reply

Add comment