I just tried the following try-catch-finally code. When i executed it, the output printed was
My question is When does the 'finally' block exactly get executed? Becuase it prints all that is there is 'try' block skips the 'return 2' statement and executes 'finally'. How does it skip that particular statement? I understand that finally is always executed even when there is exception but managing to skip exactly that particular 'return' statement in 'try' block is what puzzles me..
Is there some priority stuff in this meaning... does try-catch-finally block has more priority than a 'return' statement?
It doesn't skip the "return 2" -- it overrules it with "return 4". If a finally block returns a value or throws an exception this will overrule the return value / exception from the try or catch block. For example, the following example shows no output at all -- the exception is simply ignored.
The way to think about it is just that the code in a "finally" block always executes after the corresponding try block (and after any catch blocks that are used). The only time a "finally" block is skipped is if the thread that's executing the code is terminated, which will happen only if System.exit is called, if the JVM crashes, or if someone calls the "Thread.stop()" method. There are no notions of priority.
This means, if you think about it, that putting "return" into a finally block is virtually always a very bad idea. As you see here, if both a try and a finally include "return", then the try block's return value is ignored.
I agree with Ernest about returning from a finally block. If you need to return the same value regardless of whether or not the try block is successful or not, you should put the return statement after the try-catch-finally.
you are right that the finally block always executes even if there is an exception...so mind it that finally always executes at the end of all the blocks right..
According to your code first try block executes and prints HELLO then the return 2 statement executes but wait a minute ..you know the finally block is still there to execute..so before going back to the calling statement it will execute the finally block and will return 4 by overwriting (you can say replacing 2 from 4)....stored in a..thus the output
I think these steps made some doubts clear to you !!