gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:44:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com