Bidvertiser

Thursday, August 13, 2009

Code in a "finally" clause "may" fail to execute!!!

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,
try
{
if (userInput)
{
while (true) ;
}
else
{
System.exit(1);
}
}
finally
{
// what ever you want to clean up
}
Please 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.

5 comments:

  1. For this, you should use Runtime.getRuntime().addShutdownHook(...);

    ReplyDelete
  2. ...And even that may fail if you strike the computer with an axe.

    ReplyDelete
  3. Lol, Jose must be an axe worker I guess.

    ReplyDelete
  4. I 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.

    ReplyDelete
  5. Hi Casper,

    I am curious to know how to use "addShutdownHook() in this example?

    Please explore this.

    Thanks.

    ReplyDelete