We all would have studied that finally block always executes. 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 the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.
But here's an example where the finally code will not execute,
tryPlease note: If the JVM exits while the try or catch code is being executed, then the finally block will not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block will not execute even though the application as a whole continues.
{
if (userInput)
{
while (true) ;
}
else
{
System.exit(1);
}
}
finally
{
// what ever you want to clean up
}
For this, you should use Runtime.getRuntime().addShutdownHook(...);
ReplyDelete...And even that may fail if you strike the computer with an axe.
ReplyDeleteLol, Jose must be an axe worker I guess.
ReplyDeleteI cannot check it at the moment, but I was sure that it would work correctly with interrupted thread (as opposed to killed one) - this was one of the reasons of having well behaved interrupt method.
ReplyDeleteHi Casper,
ReplyDeleteI am curious to know how to use "addShutdownHook() in this example?
Please explore this.
Thanks.