0

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?

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • You should never have a return statement inside of a finally block. This can over-write things that were done in the try block, and can lead to really convoluted logic. – Hovercraft Full Of Eels Jan 18 '14 at 15:10
  • Anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block. – Vinayak Pingale Jan 18 '14 at 15:15

1 Answers1

6

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.

Itay Maman
  • 30,277
  • 10
  • 88
  • 118