my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception" Watch "Exception" New topic
Author

Exception

meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
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

Joined: Sep 16, 2002
Posts: 41
Because you have a "return" statement within the catch block. Take that out and you will get the missing 4 at the end.


SCJP,SCJD,SCEA,SCMAD,SCDJWS,SCJP5.0
meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
hi Manoj...not working.Without return statement also the output is 13423
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608


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".


Tony Morris
Java Q&A (FAQ, Trivia)
meena latha
Ranch Hand

Joined: Jan 24, 2005
Posts: 219
thanks i got it...
[ February 06, 2005: Message edited by: ramya jp ]
 
 
subject: Exception
 
Similar Threads
Exception
exception..try catch block execution
Doubt in Exceptions.
question about exception
Exception