gpt4 book ai didi

java - 扩展的 try-with-resources 语句到底捕获了什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:16:36 25 4
gpt4 key购买 nike

在下面的代码块中:

try ( /* resources declaration */ ) {
// some dangerous code
} catch (Exception e) {
// error handling and reporting
}

如果 try block 中的代码和自动 close() 语句都抛出异常,会发生什么情况?哪个会被 catch block 捕获?两个都?只有其中之一?如果有,是哪一个?

此外,如果 try 成功但 close 不成功怎么办?会进入 catch block 吗?

最佳答案

引自 JLS 部分 14.20.3.1 :

In a basic try-with-resources statement that manages a single resource:

  • If the initialization of the resource completes abruptly because of a throw of a value V, then the try-with-resources statement completes abruptly because of a throw of the value V.
  • If the initialization of the resource completes normally, and the try block completes abruptly because of a throw of a value V, then:

    • If the automatic closing of the resource completes normally, then the try-with-resources statement completes abruptly because of a throw of the value V.

    • If the automatic closing of the resource completes abruptly because of a throw of a value V2, then the try-with-resources statement completes abruptly because of a throw of value V with V2 added to the suppressed exception list of V.

  • If the initialization of the resource completes normally, and the try block completes normally, and the automatic closing of the resource completes abruptly because of a throw of a value V, then the try-with-resources statement completes abruptly because of a throw of the value V.

这意味着如果 try block 中的代码和自动 close() 语句都抛出异常,则 catch 部分将处理 try block 抛出的异常,异常由 suppressed exceptions 中的 close() 抛出.

此外,这意味着如果 try block 成功但自动 close() 失败,catch 仍将被执行并且捕获的异常将是 close() 抛出的异常。


这是验证此行为的测试:

public class Main {
public static void main(String[] args) throws Exception {
// try block fails and close() fails
try (T t = new T()) {
throw new Exception("thrown by try part");
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getSuppressed()[0].getMessage());
}

// try block is successful but close() fails
try (T t = new T()) {
//
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

class T implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("thrown by close");
}
}

这段代码会打印

thrown by try part
thrown by close
thrown by close

意思是捕获到的异常是第一部分代码的try部分抛出的异常。第二部分,捕获到的异常确实是close()抛出的异常。

关于java - 扩展的 try-with-resources 语句到底捕获了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34813304/

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