Can a `finally` block skip execution? When?
In most cases, the finally
block is always executed after a try
block, regardless of whether an exception was thrown or caught. However, there are rare situations where the finally
block might be skipped:
-
JVM Termination: If the JVM shuts down during the execution of the
try
orcatch
block (e.g., viaSystem.exit()
), thefinally
block will not execute.Example:
try { System.exit(0); } finally { System.out.println("This will not execute"); }
-
Thread Interruption: If the thread executing the
finally
block is forcefully terminated (e.g., bystop()
in older thread APIs), thefinally
block might be skipped. -
Infinite Loops or Errors: If there is an infinite loop or an unrecoverable error (like
StackOverflowError
) within thetry
orcatch
block, thefinally
block may not be reached.
These scenarios are exceptions, and under normal conditions, the finally
block is guaranteed to execute.