Possible Duplicate:
Does a finally block always run?
I learned that the finally clause of a try catch statement, executes always. But some guy said to me that it is possible to avoid executing it(removing it is not an option).
-Does someone how is that possible?
-Also i am curious in knowing why would someone want to avoid to execute it?
Kill it with an uncaught exception within the
finallyblock, or kill the overall JVM (which kills the thread, among other things).There is no good reason to stop the execution of a
finallyblock except poor design. If it’s not supposed to run every time, then don’t put it in afinallyblock.Using the below test code, I run two different scenarios to see what happens when killing the
Thread:Threadandsleepthe main thread for 2 seconds. Within theThread, pretty much immediately enter thefinallyblock and then sleep for 5 seconds. Once the main thread is finished waiting, kill theThreadusingstop.Threadand sleep 2 seconds. Within theThread, sleep 5 seconds before entering thefinallyblock and then sleep some more within thefinallyto give it a chance to be killed.In the first case, the result is that the
finallyblock stops executing.In the second case, the result is that the
finallyblock executes completely, and on theThreadthat wasstopped no less.Output (note the name of the current thread added for all output):
Code: