为什么return在最终块中不遵守变量的值? [英] Why return is not honoring the value of variable in finally block?

查看:111
本文介绍了为什么return在最终块中不遵守变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

finally always gets executed last, so the statement x = 3 should be executed last. But, when running this code, the value returned is 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;
    }
}


推荐答案

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

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.

这篇关于为什么return在最终块中不遵守变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆