Sobes.tech
Junior

Is the finally block always executed in a try-catch construct?

sobes.tech AI

Answer from AI

No, not always. finally may not execute in the following cases:

  • JVM terminates during the execution of the try or catch block. For example, when calling System.exit().
  • JVM crash (e.g., out of memory error or stack overflow).
  • Infinite loop in the try or catch block.
  • The thread executing the try-catch-finally block terminates.

In other cases, even if an unchecked exception is thrown or a return occurs from the try or catch block, the finally block will be executed.

public class FinallyExample {

    public static void main(String[] args) {
        try {
            System.out.println("In try block");
            // Exit JVM before finally executes
            // System.exit(0);
            throw new RuntimeException("Forced exception");
        } catch (RuntimeException e) {
            System.out.println("In catch block: " + e.getMessage());
            // Return from catch, finally still executes
            // return;
        } finally {
            System.out.println("In finally block"); // This code executes
        }
        System.out.println("After try-catch-finally"); // This code may be unreachable
    }
}