What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
- The
finallyblock always executes when thetryblock exits. - This ensures that the
finallyblock is executed even if an unexpected exception occurs. - But
finallyis useful for more than just exception handling — it allows having cleanup code accidentally bypassed by areturn,continue, orbreak. - Putting cleanup code in a
finallyblock is always a good practice, even when no exceptions are anticipated.
- If the JVM exits while the
tryorcatchcode is being executed, then thefinallyblock may not execute. - Likewise, if the thread executing the
tryorcatchcode is interrupted or killed, thefinallyblock may not execute even though the application as a whole continues.