gpt4 book ai didi

java - 带返回值的 try{} finally{} 构造

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

我想知道为什么 Java 编译器会接受以下代码:

public class Main {

public static void main(String ... args){
System.out.println("a() = " + a());
}

public static String a (){
try {
return "a";
}catch(Throwable t){
}finally{
return "b";
}
}
}

这可以而且不应该有效。 Java 规范声明 finally block 将 always 执行,但同时已经指定了返回值。所以要么你不能执行 return "b" 语句,因为你已经在 return "a" 处退出,这是不正确的。

但是,另一种选择是执行 return "b" 语句,从而完全忽略 return "a" 语句...

我会说两者都是错误的,我希望这不会编译。但是它编译并运行良好。我将把答案作为一个很好的练习留给读者;)。

基本上我的问题是:除了不好的做法之外,这是否会被视为 Java 错误,或者除了混淆之外还有其他美妙的用途吗?

编辑:

问题不在于它是否是一个已得到解答的错误,而是它有很好的用例吗?

最佳答案

一切都按预期工作,这里没有错误。当您有疑问时,JLS 是您的救星:

JLS - 14.20.2. Execution of try-finally and try-catch-finally :

If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:

  • If the finally block completes normally, then the try statement
    completes abruptly for reason R.

  • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is
    discarded).

覆盖 try block 中的值。

finally 中的

return 丢弃所有可以在 try 子句中抛出的异常。

关于java - 带返回值的 try{} finally{} 构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27527265/

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