• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confusion with finally

 
Manish Nijhawan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any one tell me that when is the finally block exceuted ??
Also what will be the o/p of the following code.

public int testMethod()
{
try
{
....
....
return 10;
}
catch(Exception ex)
{
....
....
}
finally
{
return 20;
}
}

will the value returned by this method is 10 or 20 ???
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)

 
Niki Nono
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Manish Nijhawan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()); }
}
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
--------------------------------------------------------

o/p of following comes out to be 11 instead of 10 ??

------------------------------------------------

Hi Manish

Output was 11 because return statement in try works but return statement in finally surppress return statement in try.So the result was 11.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A call to System.exit does not immediately bring down a VM.
A call to System.halt does.
 
Manish Nijhawan
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic