Reputation: 6527
I have a simple doubt. In the following two codes, in first return
statement is placed inside a finally
block
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
return 0;
}
}
And in second return
statement is placed as normal
public int method1(){
try{
// Some Stuff
} catch(Exception e){
e.printStackTrace();
} finally{
}
return 0;
}
Is there any difference between these two? And which can be used as better option? why?
Upvotes: 0
Views: 203
Reputation: 30733
It is not a good practice to have "return" in a finally block. The finally
block can be executed due to two reasons:
(a) An exception was thrown by the try
block (and not caught by catch
block) - in this case the method will have no return value so a return something
statement in the finally block will have no effect.
(b) the try
block completed normally. If that block ends with a return something
then you the code is a bit confusing to the reader, as there are now two return statements that are relevant and it is not clear which should take precedence over the other.
Upvotes: 6