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