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
}
public class Example4 {
public static void main(String[] args) {
try {
int num1 = 10;
int num2 = 0;
int result = num1 / num2; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This is the finally block.");
}
}
}
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.