will the value returned by this method is 10 or 20 ???
Manish Nijhawan<br />B-Tech
Joe Sondow
Ranch Hand
Joined: Apr 10, 2005
Posts: 195
posted
0
20. The return statement in the try block has no apparent effect if the finally block contains a return statement, or if an exception gets thrown in the finally block but not caught there. The following program produces no output other than Exception in thread "main" java.lang.RuntimeException at F.testMethod(F.java:11) at F.main(F.java:16)
SCJA 1.0 (98%), SCJP 1.4 (98%)
Niki Nono
Ranch Hand
Joined: Mar 20, 2005
Posts: 256
posted
0
finally gets executed no matter where the execution goes. in try or in catch before the function returns finally will be executed except in only one case that is when you type a System.exit() somewhere in try or catch or finally itself. this will kill the JVM and execution stops then and there.
Life called,so here I am.<br />Cheers<br />Niki.:-)
Manish Nijhawan
Greenhorn
Joined: Apr 04, 2005
Posts: 10
posted
0
It means that if there is a return statement in the try block as well as in the finally block then the try block return statement will not get executed.
am i correct ??
But if it is so then why the o/p of following comes out to be 11 instead of 10 ??
public class F { public int testMethod() { int i = 10; try { return ++i; } finally { return i; } } public static void main(String[] args) { System.out.println(new F().testMethod()); } }
Thanks a lot vidya. I have understood the concept.
Its that the return statement in the try block will be evaluated but before returning the value it will execute the finally block and inside the finally block when it encounters the return statement it will return that value.