任何人都可以解释一下附加的代码。控件如何从 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/