java - 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。为什么?什么时候终于真正被叫到这里了?
解决方案
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
推荐阅读
- git - 我无法使用 JGit 从远程存储库中签出单个文件
- ios - 如何在 swift 5 中从另一个控制器重新加载 UIViewController
- angularjs - 使用带有 AngularJS 的 trustAsHtml 显示来自输入的文本
- java - 如何在 CARML 中使用 JSONata?
- javascript - 通过计时器从状态中删除项目
- pandas - 将数据框与包含它的较大数据框相交并删除公共行
- c# - 分配字符串/匿名方法时的空引用
- angular - 错误单元测试Angular 8 / Jasmine / Karma:RangeError:超出最大调用堆栈大小
- javascript - 删除订阅
- c# - 当具有(键盘)焦点的子项被移除时,将(键盘)焦点设置为父容器