java - 尝试-捕获-最终|了解执行包含 return 语句的 try-finally block 时的控制

标签 java

任何人都可以解释一下附加的代码。控件如何从 try 转移到 finally 以及在没有 return 语句的情况下finally 将如何工作。

class TryCatchFinally{

    int ID = 0;

    public Integer test() {
        try {
            return this.ID;
        } finally {
            this.ID = 2;
        }
    }


  public static void main(String ...s) {
   TryCatchFinally obj = new TryCatchFinally();  //line 1
   System.out.println(obj.test()); //line 2
   //line 3
  }
}

实际输出是 - 0

在执行test()函数时,我将finally中的ID值更改为2。我知道我是否在第3行写入了obj.ID在 main 方法中,第 3 行的输出将为 2。我想知道,第 2 行的结果为 0。为什么?什么时候终于被叫到这里了?

最佳答案

finally block 确实发生了。来自 docs tutorial :

This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.

但是,在到达 finally block 之前,结果会“返回”(该方法不会退出,但返回值会暂时存储),因此在 return 语句时,ID 仍然为零。

public Integer test() {
    try {
        return this.ID;   //Still 0 at time of return
    } finally {
        this.ID = 2;     //This still gets executed, but after the return value is stored
    }
}

如果在方法后面打印出ID字段:

TryCatchFinally obj = new TryCatchFinally();  //line 1
System.out.println(obj.test());
System.out.println(obj.ID);

然后你会得到:

0
2

关于java - 尝试-捕获-最终|了解执行包含 return 语句的 try-finally block 时的控制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54065125/

相关文章:

java - 如何跳过测试代码或将oracle语法转换为h2

java - 是否需要重写以避免对 Java 泛型方法进行运行时类型检查?

java - 如何展示迷宫?

java - 交换 ArrayList 中的项目

java - 如何在hibernate java中使用where条件删除多条记录

Java - 转换 "this[int x, int y]"

java - GTA2 像 Car Physics,但极其简化

java - 使用套接字编程连接到我的家庭服务器

java - 当我从 Android Studio 在 Android 手机上运行应用程序时,它显示空白屏幕

java - 声明变量的最佳方式