为什么return在最终块中不遵守变量的值?

Apu*_*shi 0 java exception try-catch-finally

finally总是最后执行,因此该语句x = 3应该最后执行。但是,运行此代码时,返回的值为2。

为什么?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Max*_*mer 5

这是因为该finally块是在catch子句之后执行的。在您的内部catchreturn x,此时它的值为2,该值作为返回值写入堆栈。一旦用3 finally覆盖值x,则返回值已设置为2。