• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Catch Return statement

 
meghana chintanippu
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class mutipleReturns{
int getInt(){
int retVal =10;
try{
// some code
}
catch (exception e){
System.out.println(" about to return :"+retVal);
return retVal ; ----->1
}
finally{
System.out.println("finally");
}
return 20 ; ----> 2
}



why should there be a return statement at 2 when there is return statement at 1 ?? why is it showing compilation error if no return statement at 2??
 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should post code that compiles when asking questions but as to your question, the return at line line 1 is in catch which may or may not be executed.
There must be a return at every branch that the code can take.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meghana chintanippu wrote:why is it showing compilation error if no return statement at 2??

I'll answer your question with another question: what will the getInt-method return if some code doesn't throw any exception?
 
meghana chintanippu
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay i got it thank you so much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic