Java Programming/Keywords/finally

is a keyword which is an optional ending part of the block.

The code inside the finally block will always be executed. This is also true for cases when there is an exception or even executed statement in the try block.

Three things can happen in a try block. First, no exception is thrown:

You can see that we have passed in the block, then we have executed the  block and we have continued the execution. Now, a caught exception is thrown:

We have passed in the block until where the exception occurred, then we have executed the matching  block, the  block and we have continued the execution. Now, an uncaught exception is thrown:

We have passed in the block until where the exception occurred and we have executed the  block. NO CODE after the try-catch block has been executed. If there is an exception that happens before the try-catch block, the block is not executed.

If statement is used inside finally, it overrides the return statement in the try-catch block. For instance, the construct

will return 12, not 11. Professional code almost never contains statements that alter execution order (like, , ) inside the finally block, as such code is more difficult to read and maintain.

See also:
 * Java Programming/Keywords/try
 * Java Programming/Keywords/catch
 * Java Programming/Throwing and Catching Exceptions