This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
I thought it would print finally2 as the O/P. But the compiler showed, catch1, finally1, finally2???
My doubt here is that the call t.f();, the method f() throws Run time exception which is not caught...so the flow should not have gone inside the catch(Throwable e)....Am I right or wrong??
In java Thowable is super class of all exception and error. Since your are throwing new RunTimeException inside f() method, it has matching catch cause.
Now since you have both catch and finally clause, first precedence is for catch casue.
Then you are catsing Throwable object to Exception object which is valid.
also for that you have matching catch statement. so it will get executed firstly.
catch1 will be printed. then inner finally will executed and will print finally1 and at last outer finally will get executed and will print finally 2.
Jothi, Sorry for replying after you have got the hidden trick.I have something to add in your reply..
My doubt here is that the call t.f();, the method f() throws Run time exception which is not caught...so the flow should not have gone inside the catch(Throwable e)....Am I right or wrong??
This is wrong all runtime exceptions and subclasses of Error are non-checked it simply means that they are meant to be thrown at the time when the program runs(not compiles),it never means that they are not caught when thrown explicitly or implicitly.
when I was looking at the code I thought:"Hey, this cannot compile."
Something seemed wrong to me with the nesting. I tried out and really, this was not only due to this silly indentation (call it "exam baroque") but there was also a } bracket missing.
I find, when better indentated (ok, can't be done at exam time) the answer is easier:
Perhaps the question also wants to test, if you know, that you can rethrow an exception that is smaller than the one just caught?
what is the purpose of rethrowing the exception? or what will rethrow exception will do?
I can think of two reasons you might want to rethrow an exception:
1. Your method might need to catch the exception so that it can clean up any resources it has allocated before rethrowing the exception so that the caller of the method knows that something went wrong.
2. You may want to add some more information to any exceptions you catch in a method. So you catch the exception and extract any relevant information from it. You then create a new exception that combines information from the original exception with any extra information you want to add and then trow that exception.