Code outside the finally block is not guaranteed to execute. Let's say some sort of unchecked exception happened that wasn't caught, or somewhere in the try block you execute the return statement; then code below the finally block would not be executed. Code inside the finally block is *always* executed, even if an exception was raised and left uncaught, or if the method returned abruptly.
Joined: Mar 13, 2008
What if there was a exception in finally block itself?
Raj Srimandal wrote:What if there was a exception in finally block itself?
Hmm... that is your responsibility to code to not throw any exception from finally block.
for an example:
if an exeception is thrown before close(), then dbConnection close is failed. then dbConnection object can not be garbage collected, since it is a system resource. so probably you need to wrap try catch around the exception and log the error message like below
rule of thumb:do not throw an Exception and do not use return statement in finally block.finally block should be execute normally.
Stephan van Hulst wrote:Code inside the finally block is *always* executed
Unless System.exit() is executed in either the try or catch block.
... or System.exit() is called in another thread, or this try/finally is in a daemon thread and all the non-daemon threads complete, or the JVM dumps core, or someone pulls the plug, or a meteor destroys the earth, or...
There are an infinity of scenarios in which it won't run, so just enumerating one of them opens the door to a can of incompletion and confusion-shaped worms.
A more precise and cover-all-the-bases way to put it would be something like, "As long as the thread continues executing, finally is guaranteed to execute after the try and a catch block if one was invoked, before transferring control to the next statement or back up the stack to the calling method."