gpt4 book ai didi

java - try-catch-finally 后返回

转载 作者:IT老高 更新时间:2023-10-28 20:52:09 28 4
gpt4 key购买 nike

我知道 try、catch 和 finally 是如何工作的(大部分情况下),但我有一件我想知道的事情:在 try-catch-finally 之后的 return 语句会发生什么,而我们已经在 try 中有一个 return (或捕获)?

例如:

public boolean someMethod(){
boolean finished = false;
try{
// do something
return true;
}
catch(someException e){
// do something
}
finally{
// do something
}
return finished;
}

假设尝试没有出错,所以我们返回 true。然后我们会去 finally 我们做一些像关闭一个连接的事情,然后呢?

我们在finally中做了一些事情之后方法会停止(所以方法在try中返回true),还是在finally之后方法继续,导致返回finished(即假)?

提前感谢您的回复。

最佳答案

finally block 被执行的事实不会让程序忘记你返回。如果一切顺利,finally block 之后的代码就不会被执行。

这是一个清楚的例子:

public class Main {

public static void main(String[] args) {
System.out.println("Normal: " + testNormal());
System.out.println("Exception: " + testException());
}

public static int testNormal() {
try {
// no exception
return 0;
} catch (Exception e) {
System.out.println("[normal] Exception caught");
} finally {
System.out.println("[normal] Finally");
}
System.out.println("[normal] Rest of code");
return -1;
}

public static int testException() {
try {
throw new Exception();
} catch (Exception e) {
System.out.println("[except] Exception caught");
} finally {
System.out.println("[except] Finally");
}
System.out.println("[except] Rest of code");
return -1;
}

}

输出:

[normal] Finally
Normal: 0
[except] Exception caught
[except] Finally
[except] Rest of code
Exception: -1

关于java - try-catch-finally 后返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533128/

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