This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
" this code should right away give error when throwing ex in inner catch block exception not handeled. how does above code prints catchfinally1finally2 .it goes fine when i un comment line 1 "
I am not sure whether I understood the question, but it goes to finally block before throwing the exception. If you have the exit uncommented, it won't throw exception because it exits execution before throwing.
First of all the code will not give any compilation error as you have declared Exception in the throws clause of the main method.
Now lets go through the execution of the program...
The exception thrown at (1) is caught at (2).
another exception is thrown at (3) which is again caught at (4)
Line (5) is executed and "Catch" is displayed.
Another exception is thrown at (6) which is not caught.
As you know finally is always executed whether try or any catch trows any exception or run successfully or return any value. So the finally associated with try(2) is executed. Here Finally1 is displayed at (7) so total "CatchFinally1" has been displayed till now.
Now the finally associated with try(1) is executed which displays Finally2 at (8). So "CatchFinally1Finally2" is displayed at the end.
Now if you comment line (9) then Exception is thrown. If you uncomment line (9) then the program exits without throwing any exception.