首页 > 解决方案 > Try-Catch-Final | 试一试 | 执行try-finally块时控制的理解包含return语句

问题描述

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

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()函数时,我最终将 ID 的值更改为 2。我知道如果我obj.ID在 main 方法中写入第 3 行,第 3 行输出将为 2。我想在这里知道,我得到的第 2 行的结果为 0。为什么?什么时候终于真正被叫到这里了?

标签: java

解决方案


finally阻塞确实发生。从文档教程

这样可以确保即使发生意外异常也会执行 finally 块。但 finally 不仅仅对异常处理有用——它允许程序员避免清理代码意外地被 return、continue 或 break 绕过。

然而,在到达块之前,结果被“返回”(该方法没有退出,但返回值被临时存储)finally,所以在返回语句时,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

推荐阅读