Does a finally block always get executed in Java?

In Java, a finally block is almost always executed, but there are rare exceptions where it may not run. Here’s a breakdown of when it executes and when it doesn’t:

When the finally Block Executes

The finally block runs regardless of whether:

  1. The try block completes normally.
  2. An exception is thrown and caught in a catch block.
  3. An exception is thrown and not caught (e.g., unhandled exception).
  4. A return, break, or continue statement exits the try/catch block.

Example:

try {
    // Code that may throw an exception
    System.out.println("Inside try");
    throw new RuntimeException();
} catch (Exception e) {
    System.out.println("Inside catch");
    return; // Finally still runs before returning
} finally {
    System.out.println("Finally block executed");
}
// Output:
// Inside try
// Inside catch
// Finally block executed

When the finally Block Does NOT Execute

  1. JVM Termination:
    If the JVM exits abruptly (e.g., System.exit() in try/catch), the finally block is skipped.
   try {
       System.out.println("Inside try");
       System.exit(0); // JVM terminates here
   } finally {
       System.out.println("This never runs");
   }
  1. Infinite Loop/Halt:
    If the try/catch enters an infinite loop or the OS halts the process, finally won’t run.
   try {
       while (true) {} // Infinite loop
   } finally {
       System.out.println("Never reached");
   }
  1. Daemon Threads:
    If the JVM exits while a daemon thread is executing try/catch, finally may not run.
  2. Critical System Errors:
    If the JVM crashes due to an unrecoverable error (e.g., OutOfMemoryError, OS kill signal), finally is skipped.

Key Takeaways

Scenariofinally Executes?
Normal execution✅ Yes
Uncaught exception✅ Yes
return in try/catch✅ Yes
System.exit()❌ No
JVM crash/process killed❌ No
Infinite loop in try/catch❌ No

Best Practices

  • Avoid relying on finally for critical cleanup if System.exit() is used.
  • Use finally for releasing resources (e.g., closing files, database connections).
  • For guaranteed cleanup, consider try-with-resources for auto-closeable resources.

The finally block is a powerful tool for ensuring code runs in most scenarios, but be aware of its edge cases!

Leave a Reply

Your email address will not be published. Required fields are marked *