If I compile and run the above code, "3" is printed. Can somebody please explain : 1. Why is a compilation error not thrown since method() is not throwing the Exception ? 2. A new Exception is thrown in catch block. How does "3" get printed since the that Exception is not handled ?
Because you have a return statement in your finally block. If you remove the return statement your code will not compile. A return statement in a finally block will hide your exceptions. So it is not wise to do so.
Yes, if you "return" or "throw" in a "finally" block, any pending exception is lost. Therefore, you should never "return" or "throw" in a "finally" block.
It is pretty easy to remember not to use "return" or "throw" in a "finally". But it is also necessary to ensure that any method calls in your "finally" cannot reasonably throw an exception, because that exception would hide the pending exception.
To do this: -
Keep code in "finally" as simple as possible
Use try..catch, inside the "finally", to handle any exceptions that occur. Usually, there is little you can do beyond logging the exception, as you already have another exception pending.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
Here's another way to look at this: An exception means that there's some problem preventing your code from proceeding as intended, so it breaks out of the method body and passes control elsewhere (the catch block). However, if you place a return statement in the finally block, then your method ends up returning normally, and execution continues from where the method was called, as if no exception were thrown.
A finally block is for code that should execute in all cases -- whether or not an exception is thrown.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Rakesh Ne
Greenhorn
Joined: Mar 12, 2007
Posts: 14
posted
0
Thanks for your replies. I am still in a confusion over the compilation error
Even though we have the catch block throwing Exception, the method signature does not have throws Exception public static int method(){...}
Why does the compiler not complain ?
My guess - The code will never reach that stage. Hence it is supressed.