gpt4 book ai didi

java - 从finally block 返回一个值

转载 作者:行者123 更新时间:2023-12-02 04:47:39 26 4
gpt4 key购买 nike

我在一个java认证网站上找到了这段代码

   public class Test1{
public static void main(String args[]){
System.out.println(method());
}
public static int method(){
try{
return 1;
}
catch(Exception e){
return 2;
}
finally{
return 3;
}
}
}

所以这段代码的输出结果如3所示。这怎么可能……因为它在 try block 本身中返回 1?代码永远不会到达finally,对吗?

最佳答案

代码永远不会到达finally,对吗?不,如果有finally block 控制会在try或/and catch之后转到finally

因为无论如何finally总会执行。除了 Mike Kobit 所说的System.exit

感谢 Jason C,来自 JLS 14.17. The return Statement

It can be seen, then, that a return statement always completes abruptly.

The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any try statements (§14.20) within the method or constructor whose try blocks or catch clauses contain the return statement, then any finally clauses of those try statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a finally clause can disrupt the transfer of control initiated by a return statement.

来自JLS 14.20.2. Execution of try-finally and try-catch-finally

If execution of the try block completes normally, then the finally block is executed, and then there is a choice:

  1. If the finally block completes normally, then the try statement completes normally.
  2. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

因此,在您的代码中,try 返回 1,然后控制转到最终返回 3。因此函数的返回值将为 3。

关于java - 从finally block 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29530777/

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