gpt4 book ai didi

java - try-with-resources 中的 catch 是否覆盖了括号中的代码?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:54 25 4
gpt4 key购买 nike

不清楚documentation try-with-resources 之后的 catch 是否覆盖了初始化部分。

换句话说,给定这段代码:

    try (InputStream in = getSomeStream()) {
System.out.println(in.read());
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}

如果在 getSomeStream() 中抛出 IOException,是否会调用我的 catch

或者 catch 是否只覆盖大括号内的 block ,即 System.out.println(in.read())

最佳答案

来自JLS ,您的示例是扩展的 try-with-resources。

A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

在那种情况下:

The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

是的,异常将被您的 catch block 捕获。

关于java - try-with-resources 中的 catch 是否覆盖了括号中的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43522560/

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