What will happen if you put the return statement or System.exit () on the ‘try‘ or ‘catch‘ block? Will the ‘finally’ block execute?

If you put the return statement inside the try or catch block, the finally block will still execute before the method returns or the program terminates. However, if you put System.exit() inside the try or catch block, the finally block will not execute. Let's what happens in both cases.

The return statement inside try or catch block:

If a return statement is encountered inside the try or catch block, the control immediately exits the try or catch block, and the finally block will execute before the method returns the value. The finally block ensures that any cleanup or resource-releasing code is executed regardless of whether an exception occurred or not.
public class FinallyBlockExample {
    public static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
            return -1; // This will be executed before finally block
        } finally {
            System.out.println("Finally block is executed.");
        }
    }

    public static void main(String[] args) {
        int result = divide(10, 0);
        System.out.println("Result: " + result);
    }
}

Output:

Exception caught: / by zero
Finally block is executed.
Result: -1

System.exit() inside try or catch block: 

If System.exit() is called inside the try or catch block, the Java Virtual Machine (JVM) terminates the program immediately, and the finally block will not execute. The finally block is skipped because System.exit() causes the program to terminate abruptly.

public class FinallyBlockExample {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block");
            System.exit(0); // JVM will terminate here, finally block won't execute
        } catch (Exception e) {
            System.out.println("Exception caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block is executed."); // This won't be executed
        }
    }
}

Output:

Inside try block
To summarize, if a return statement is used inside the try or catch block, the finally block will execute. However, if System.exit() is used inside the try or catch block, the finally block will be skipped, and the program will terminate immediately.

Comments