Java › Exceptions
What is the finally block's execution guarantee, and what are the specific edge cases where a finally block might NOT execute?
IntermediateAnswer
A finally block is guaranteed to execute after the corresponding try (and any matching catch) block completes, whether execution left normally, via a caught exception, an uncaught exception propagating out, or even a return/break/continue statement inside the try/catch -- the notable exceptions to this guarantee are: the JVM itself terminating abruptly (System.exit(), a JVM crash, or the process being killed), an infinite loop or blocking call within the try block that never actually returns control, or a Thread.stop() call (a deprecated, dangerous, unsafe method) -- outside these edge cases, finally is an extremely reliable guarantee for cleanup code.
public int riskyMethod() {
try {
return 1;
} finally {
System.out.println("finally still runs even though try already returned!");
// Note: a return statement HERE would actually override/discard the try block's return value --
// a well-known finally pitfall, generally considered bad practice
}
}Real-world example A resource-cleanup routine placed in a finally block reliably executes even when the corresponding try block's code throws an unexpected exception or returns early, EXCEPT in the rare case where the entire JVM process is forcibly terminated via System.exit() elsewhere in the code, an important edge case to be aware of for critical cleanup logic.