• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception..try catch block execution

 
pravin kumar
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there is return statement in the catch block.Before the return is executed finally block will be executed.
 
Harshil Mehta
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, I think it's not advisable to return a value from finally block.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic