【问题标题】:Return statement in try and finally [duplicate]在 try 和 finally 中返回语句 [重复]
【发布时间】:2014-02-28 01:29:01
【问题描述】:

请检查以下代码并解释输出行为:

    class ExceptionTest2 {
        int x = 5;

        public int TestMethod2() {
            try {
                x = x + 2;
                System.out.println("x value in try: " + x);
                return x;
            } catch (Exception e) {

            } finally {
                x = x + 3;
                System.out.println("x value in finally: " + x);
            }
            return x;
        }

    }

    public class ExceptionProg2 {

        public static void main(String[] args) {
            ExceptionTest2 test2 = new ExceptionTest2();
            int res = test2.TestMethod2();
            System.out.println("Res : " + res); // it should return 10 but returning 7.
        }

    }

这里返回 7 而不是 10。

这是实际的o/p:

x value in try: 7
x value in finally: 10
Res : 7

为什么会这样,当 x 值在 finally 块中更改并且 'x' 不是局部变量时。

请澄清我的疑问。

【问题讨论】:

标签: java try-catch


【解决方案1】:

当 X 从 try 块返回时,该值将存储在该方法的堆栈帧中,然后执行 finally 块。

【讨论】:

  • 但是存储在堆栈帧中的值正在正确更改!!!
  • @Sandy:错了。实例成员正在更改,但堆栈上的值是实例成员中值的副本,而不是对其的引用。 完全 喜欢:x = 5; int y = x; x = x + 3; System.out.println(y); 输出 5,而不是 8
  • 不,堆栈的值不会改变,但是如果你从 finally 块返回值,那么是的,值会改变..
  • @Crowder:谢谢。现在对我来说很清楚。对于 premitive return 语句保持正确的值!但是对于对象引用,它拥有引用吗?例如,从 try 中返回 StringBuilder 并在 finally 块中附加一些内容。请解释一下。
猜你喜欢
  • 2010-11-25
  • 2016-03-28
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 2015-02-16
  • 2017-07-20
  • 2021-02-14
  • 1970-01-01
相关资源
最近更新 更多