【问题标题】:Java finally block changes value of class variable but not return statement in Try block [duplicate]Java finally 块更改类变量的值,但不更改 Try 块中的返回语句 [重复]
【发布时间】:2019-12-23 06:43:48
【问题描述】:

我已经看到这种行为被解释了,因为它通常是 finally 块中的不可变字符串,但我不明白为什么 int 原语会以这种方式表现。

"i" 不是按值作为方法中的参数传递的。该方法是直接设置 i 类变量。这是显而易见的,因为在方法完成后打印时 i 的值会发生变化。

同样清楚的是,它在 try 块中的 return 语句之前已被更改,因为 finally 块中的 print 首先打印。

public class Test {
    static int i = 0;
    public static void main(String[] args) {

        System.out.println("Try Block returns: " + methodReturningValue());
        System.out.println("Value of i after method execution is " + i);
    }


    static int methodReturningValue()
        {


            try
            {
                i = 1;
                System.out.println("try block is about to return with an i value of: "+  i);
                return i;
            }
            catch (Exception e)
            {
                i = 2;
                return i;
            }
            finally
            {
                i = 3;
                System.out.println("Finally block: i has been changed to 3");
            }
        }


    }

输出:

try block is about to return with an i value of: 1
Finally block: i has been changed to 3
Try Block returns: 1
Value of i after method execution is 3

【问题讨论】:

  • “我已经看到这种行为被解释了,因为它通常是一个不可变的字符串” 你在哪里看到过这种解释?这种解释根本没有意义。在 finally 中为字段或变量分配不同的值不会影响使用 return 的返回值。 Java 是按值传递,而不是按引用传递。
  • 传递了一些东西:返回值从方法中传递给调用者。但是,我认为您将在变量中重新分配新值与更改变量引用的对象的内容混淆了。
  • 没错。评估顺序,而不是不变性等。

标签: java try-catch-finally finally


【解决方案1】:

是的,finally 块总是在“返回”和“抛出”异常之后运行,您的代码与以下内容相同:

public class Test {
    static int i = 0;
    public static void main(String[] args) {

        System.out.println(methodReturningValue());
        System.out.println(i);
    }


    static int methodReturningValue()
    {

        int answer = 0;
        try
        {
            i = 1;
            answer = i;
        }
        catch (Exception e)
        {
            i = 2;
            answer = i;
        }
        i = 3;
        System.out.println("i=3");
        return answer;
    }


}

【讨论】:

  • dung ta van,它不是在“返回”之前运行吗?这不是打印语句所表明的吗?
  • dung ta van,检查输出。 finally 块在 try 返回之前执行。 : i 在尝试块返回之前已更改为 3 尝试块返回:1 方法执行后 i 的值是:3
  • 我不知道你的意思,如果finally 存在,该函数将创建一个临时变量(答案)。它首先打印(i = 3)并在之后返回'答案',因为'答案'的类型是int(值类型)所以它的值没有改变,如果你使用AtomicInteger你会得到答案'i = 3, 3, 3`
  • 公共类测试 { 静态 AtomicInteger i = new AtomicInteger(); public static void main(String[] args) { System.out.println(methodReturningValue()); System.out.println(i); } 静态 AtomicInteger 方法ReturningValue() { 尝试 { i.set(1);返回我; } 捕捉(异常 e){ i.set(2);返回我; } 最后 { i.set(3); System.out.println("i=3"); } } }
  • 问题是为什么 OP 的代码 工作方式与此代码相同。它肯定不会。
猜你喜欢
  • 2013-04-08
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 2014-02-28
  • 1970-01-01
相关资源
最近更新 更多