Why return is not honoring the value of variable in finally block? [duplicate]

二次信任 提交于 2019-12-01 12:47:07

问题


finally always gets executed last, so the statement x = 3 should be executed last. But, when running this code, the value returned is 2.

Why?

class Test {
    public static void main (String[] args) {
        System.out.println(fina());
    }

    public static int fina()
    {
        int x = 0;
        try {
            x = 1;
            int a = 10/0;
        }
        catch (Exception e)
        {
            x = 2;
            return x;
        }
        finally
        {
            x = 3;
        }
        return x;
    }
}

回答1:


That's because the finally block is executed after the catch clause. Inside your catch you return x, and at that point its value is 2, which gets written to the stack as return value. Once finally overwrites the value of x with 3, the return value is already set to 2.




回答2:


This is because you have a return statement in a catch block. Code is returning the value from that return statement even if the value is redefined in finally Block.



来源:https://stackoverflow.com/questions/57929659/why-return-is-not-honoring-the-value-of-variable-in-finally-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!