Originally posted by Javier Sanchez Cerrillo:
...
1.- I'm amazed why the compiler doesn't complain for a missing return statement!!!.
Once I execute this code the exception on line 1 stops the program. As expected. But....:
2.- If I replace line 2 for: return "Finally", the program compiles and run fine and its output is:
Finally
Why the exception is not caught this time?
Does it have something to do to what meena kumari pointed out?
In your example, an exception will
always be thrown, so the method is not required to return normally. But if you make the exception a
possibility instead of a certainty, then the compiler will require a return statement. For example...
And yes, as meena pointed out, if the finally block includes a return statement, then the method will return normally (i.e., control will be passed to the point at which the method was called). And in this situation, whatever was caught will basically be "lost." However, I would point out that this is probably a misuse of finally, because if an exception is thrown, do you
really want your method to return? The finally statement is basically for cleanup that should be performed even if the method does
not return normally.