• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test
{

public static String output="";
public static void foo(int i)
{
try{
if(i==1)
{
throw new Exception();
}

System.out.println(output +="1");

}

catch(Exception e)
{
System.out.println(output+="2");
return;
}
finally{
System.out.println(output+="3");
}
System.out.println(output+="4");
}


public static void main(String[]arf)
{
foo(0);
foo(1);
}
}

I thought the output will be 134234,but the output is 13423.
Why when the Exception is throw System.out.println(output+="4") not executed......can anybody explain this.
 
manoj pillai
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you have a "return" statement within the catch block. Take that out and you will get the missing 4 at the end.
 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Manoj...not working.Without return statement also the output is 13423
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What makes you think you will get that output?
Your first run through throws no exception, so you see "1", then the finally block executes (as always), so you see "3", and then you see "4".
Your second run through throws an exception, so you see "2", then the finally block executes so you see "3", then you return.
Your output is "13423".

If you remove the return statement, the output is "134234".
 
meena latha
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks i got it...
[ February 06, 2005: Message edited by: ramya jp ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic