The finally clause is always executed regardless whether an exception occurred or not. Occasionally, you may want some code to be executed regardless of whether an exception occurs or is caught. Java has a finally clause that can be used to accomplish this objective.
The syntax for the finally clause might look like this:
try {
statements;
}
catch (TheException ex) {
handling ex;
}
finally {
finalStatements;
}
The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught. Consider three possible cases:
- If no exception arises in the try block, finalStatements is executed, and the next statement after the try statement is executed.
- If a statement causes an exception in the try block that is caught in a catch block, the rest of the statements in the try block are skipped, the catch block is executed, and the finally clause is executed. The next statement after the try statement is executed.
- If one of the statements causes an exception that is not caught in any catch block, the other statements in the try block are skipped, the finally clause is executed, and the exception is passed to the caller of this method.
The finally block executes even if there is a return statement prior to reaching the finally block. The catch block may be omitted when the finally clause is used.