Finally Block

The finally Block:

The finally block is used to execute important code such as closing resources, regardless of whether an exception was thrown or not. The finally block always executes after the try-catch blocks.

A finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. Even if there is a return statement in the try block, the finally block executes right after the return statement is encountered and before the return executes i.e finally block got the first priority.

Syntax:

try {
    // Code that might throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
} finally {
    // Code that will always execute
}
Code Example
Output
Cannot divide by zero.
This is the finally block.

Explanation:

Even though an ArithmeticException occurs and is caught by the catch block, the finally block still executes.