when does the finally block not execute while try or catch block is interrupted? the doc says that "if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues." can someone give an example about this situation?
Good answers can be found here.
Besides a System.exit()
, the finally block will not run if the JVM crashes for some reason (e.g. infinite loop in your try
block).
As far as the thread itself, only if it is stopped using the stop()
method (or suspend()
without resume()
) will the finally
block not be executed. A call to interrupt()
will still result in the finally
block being executed.
It's also worth noting that, since any return
statement in the finally
block will override any returns or exception throws in the try
/catch
blocks, program behavior can quickly become erratic and hard to debug if this happens to you. Not really anything worth taking precaution against (as it only happens in extremely rare cases), but worth being aware of so you can recognize it when it happens.
The only legal way to make finally
not execute is to call System.exit
or Runtime.halt
in try
or catch
Abruptly ending the application before it, e.g.
System.exit();
Even the return before finally
block (e.g. in try
block) will be executed after the finally
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With