javareturntry-catchfinally

Is placing return statement before finally block a good practice?


I was wondering if below code is correct according to Java standards. Can return statement be placed after try block ? or is it always good to place return statement in finally block. Please help me out on this

public int method()
{
    try{
        //code
        return 1;
    }
    catch(Exception e){
        return 0;
    }
    finally{
    }
}

Solution

  • Putting return in the try or even in the catches is absolutely fine: do whatever is clearest. Take care not to discard too many exceptions though, particularly java.lang.Throwable as doing that can interfere with the workings of the JVM.

    Note that if you have a return in the finally block, then the expression in the other return is still evaluated but the result is discarded and the return value in the finally block is returned back to the caller. Because of this, putting a return value in the finally block is discouraged.