File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes exception..try catch block execution Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "exception..try catch block execution" Watch "exception..try catch block execution" New topic
Author

exception..try catch block execution

pravin kumar
Ranch Hand

Joined: Nov 03, 2005
Posts: 30
public class Test {
public static String output ="";

public static String foo(int i) {
try{
if(i==1) {
throw new Exception();
}
output += "1";
}
catch(Exception e) {
output += "2";
return output;
}

finally {
output += "3";
}
output += "4";
//return output;
}
public static void main(String args[]) {
foo(1);
System.out.println("The output after foo(1) is:"+output);
}
}


here code goes go catch block..i just wanted to know tht can't we put
return statement in catch block rather than after finally


Please sorry if it is inane question
Rajat Gupta
Greenhorn

Joined: Sep 16, 2005
Posts: 7
Pravin,

What I understand, you can put the return statement anywhere in the try or the catch block, but if there is a "Finally" block, it will be executed, no matter what. Hope this answers the query.

Cheers,
Rajat
Balaji Sampath
Ranch Hand

Joined: Sep 30, 2005
Posts: 63
Just an addtion:
when u put return in catch block the ouput is :"123" but when u put the return after finally then output modified to "1234".

Regards
Balaji.A
Deepak Sagar
Greenhorn

Joined: Dec 18, 2005
Posts: 6
just want to add one thing.
when control goes to return part of catch, it wl go to finally. If there is return in both catch and finally, it wl take the value returned through finally. or else it will take the value returned through catch..

catch(Exception e) {
output += "2";
return "CATCH";
}

finally {
output += "3";
if(true);
return "FINALLY";
}
this wl return string "FINALLY". as there is reurn in both catch and finally.



catch(Exception e) {
output += "2";
return "CATCH";
}

finally {
output += "3";
}
it wl return string "CATCH" as there is no return in catch part.
manogna edintipal
Ranch Hand

Joined: Aug 16, 2005
Posts: 51
If there is return statement in the catch block.Before the return is executed finally block will be executed.


Sanju
Harshil Mehta
Ranch Hand

Joined: Mar 17, 2005
Posts: 64
However, I think it's not advisable to return a value from finally block.
 
Don't get me started about those stupid light bulbs.
 
subject: exception..try catch block execution