Behaviour of return statement in catch and finally

Ammu picture Ammu · Apr 18, 2011 · Viewed 59.2k times · Source

Please see the following code and explain the output behavior.

public class MyFinalTest {

    public int doMethod(){
        try{
            throw new Exception();
        }
        catch(Exception ex){
            return 5;
        }
        finally{
            return 10;
        }
    }

    public static void main(String[] args) {

        MyFinalTest testEx = new MyFinalTest();
        int rVal = testEx.doMethod();
        System.out.println("The return Val : "+rVal);
    }

}

The result is the return Val : 10.

Eclipse shows a warning: finally block does not complete normally.

What happens to the return statement in catch block ?

Answer

Bozho picture Bozho · Apr 18, 2011

It is overridden by the one in finally, because finally is executed after everything else.

That's why, a rule of thumb - never return from finally. Eclipse, for example, shows a warnings for that snippet: "finally block does not complete normally"