The finally block in Java is used to execute important code such as resource cleanup. It always runs whether an exception occurs or not.
return is usedThe finally block follows try and optional catch blocks. It ensures cleanup code runs reliably.
// Basic structure of try-catch-finally
try {
System.out.println("Inside try block");
}
catch(Exception e) {
System.out.println("Exception caught");
}
finally {
System.out.println("Finally block always runs");
}
// Example showing finally execution even with exception
public class FinallyDemo {
public static void main(String[] args) {
try {
int a = 10 / 0;
}
catch(ArithmeticException e) {
System.out.println("Division by zero");
}
finally {
System.out.println("Cleaning up resources");
}
}
}
Division by zero
Cleaning up resources
Even though an exception occurs, the finally block executes without fail.
Experiment with the simulator to prove that finally runs no matter what happens in the try block.
finallyfinally