Does a finally block always get executed in Java?
The finally block is designed to execute after try-catch, used for clean-up operations. It executes irrespective of exceptions that could occur. However, scenarios such as JVM termination via System.exit(), JVM crash, infinite iterations in try, or external system incidents may prevent its execution. Here's an elementary scenario:
However, if a System.exit() is invoked in the try, then the finally block will not execute:
Hence, finally is reliable except for certain system-level events or explicit JVM termination commands.
Drill-down explanation
Though the finally block is designed to execute always, certain scenarios and program constructs can alter this expected behavior.
- Return values override: A
returnstatement within afinallyblock can override any return values from thetryorcatchblocks. - Exception override: An exception in
finallyblock will supersede the one from thetryblock. - Non-terminating loops: If
trycontains a loop which never terminates,finallywill not execute. - Thread death: Death of the thread executing the
try-finallyblock may lead to incomplete execution offinally.
Exception scenarios
In some extreme conditions, the finally block might not execute:
- Daemon threads: If the JVM doesn't wait for daemon threads to execute their
finally, all non-daemon threads will complete their execution, potentially skipping thefinallyexecution. - Power/System Failure: System crash before the
finallyblock execution will prevent thefinallyfrom execution. - JVM or OS issues: The
finallyblock may not execute if the JVM encounters a severe error or if the operating system is affected. - External forces: Commands like
kill -9or hardware-level failures that force-stop the JVM will also preventfinallyfrom executing.
Best practices and gotchas
For best usage of finally block, follow these guidelines:
- Avoid altering the program flow by using
return,throw, or other flow-altering statements in afinallyblock. - Handle resources neatly with Java 7’s try-with-resources statement, you can manage resources without calling
finally. - Handling of threads: remember that running
finallyblocks are not guaranteed before the JVM shuts down in scenarios involving daemon threads and shutdown hooks.
Follow these practices to harness the finally block's full potential whilst avoiding pitfalls.
Was this article helpful?