First off, the output is: catch has assigned i the value 1. finally has assigned i the value 2. The output of t.someMethod() = 1 An exception is thrown within the try block, so the catch block will, well, catch it and assign 1 to i. Then, when the return statement is encountered, the value of i is stored somewhere as the return value. Just before returning, the finally block is executed, the assignment of 2 to i has no effect. The finally block ends and the method returns... HIH
hi my question here is :its not guaranteed that the catch statement is always executed as mentioned in another thread, and the compiler knows that in try catch finally block the finally block is always executed even if no exceptions result from try. so why the compiler didn't say: "missing return statement"? i compiled it and i see it runs fine but i'm wondering if there is an explanation .i know there is agood one but i don't know it.
Aymen Esawey<br />SCJP <img src="smile.gif" border="0"> <br /><a href="http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=32&t=001968" target="_blank" rel="nofollow">how to nuke the SUN </a>
The compiler is smart enought o know all of the possible ways for the method to exit and can check them for proper return values. Inthe example given the code will always throw an Exception so the catch will always be exectued and the method will always return a value as required. To see the compiler check the code look at this:
When compiled the way it is above the compiler will produce an error saying the method does not return a value because with line 1 commented out and line 2 uncommented it will throw an uncaught NumberFormatException, so the exception is thrown then finally executes and at no point does it get to a return statement. If you uncomment line 1 and comment line 2 it will still give you an error because you have a catch block that does not have a return statement. So the compiler can figure out all of the exits from your method and test the for correctness - that's why you dont get an error in the original code. This example uses RuntimeExceptions but the principle will be the same for checked Exceptions too. hope that helps clear it up for you