The indentation is bad. This should be more clear:
Now what the code does is the following:
It goes into the first try block and prints 'In try 1'.
Then it throws an exception, which is immediately caught by the first catch block, which prints 'In catch 1'.
The catch block then proceeds to the second try block, which prints 'In try 2' and then attempts to return.
No exceptions are thrown, so the second catch block is skipped. The finally block *is* run though, because finally *always* executes.
So, the program then prints 'In finally 2', after which it continues to the third try block.
This block prints 'In try 3', and then immediately attempts to return.
No exceptions are thrown, so the third catch block is skipped. Again, the finally block *is* run, overruling the previous return commands.
The program prints 'In finally 3', after which the third try/catch/finally statement is finished.
The method now returns, because that was the last statement executed in the third try block, before the finally block was executed.
Simply said, the return statement in the second try block *is* reached, but the second return statement takes precedence, because it's nested in the finally block.
The lesson is, under no circumstances call return in a finally block.
Stephan van Hulst wrote:
The finally block *is* run though, because finally *always* executes.
This is correct, but considering the assumption that finally won't execute in case of JVM Shutdown The shutdown may be because of calling System.exit(0), or by killing the JVM process through Task Manager, or if machine crashes etc.
finally won't be executed in the following code:
But finally runs in all other cases
Joined: Sep 23, 2010
Thank you Stephan. You gave wonderful explanation and I will start using the new format. Could please advice how did you change the indentation. What I mean is did you change the format manually (or) automatically..If automatically, How did you do it.
Answers to my questions are given below.
Answer to Question 1: Once if control executes return, It will come out of the method. That's why first return statement at Line 14/or any other code is not executed.
Answer to Question 2: try-catch-finally should be completed before return (In case of inner statements, inner return takes precedence at Line 28 than outer return at Line 14)is executed.