- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
在下面的代码块中:
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 valueV
, then the try-with-resources statement completes abruptly because of athrow
of the valueV
.If the initialization of the resource completes normally, and the
try
block completes abruptly because of athrow
of a valueV
, then:
If the automatic closing of the resource completes normally, then the try-with-resources statement completes abruptly because of a
throw
of the valueV
.If the automatic closing of the resource completes abruptly because of a
throw
of a valueV2
, then the try-with-resources statement completes abruptly because of athrow
of valueV
withV2
added to the suppressed exception list ofV
.- 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 valueV
, then the try-with-resources statement completes abruptly because of athrow
of the valueV
.
这意味着如果 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/
这对你们来说可能很简单,但由于我是java新手,所以我想知道实际上什么是 接下来的部分会发生什么? if (args.length > 0) { file = args[0]; } publi
在我的 View Controller 中,我将 UITapGestureRecognizer 添加到 self.view。我在 self.view 之上添加了一个小 View 。当我点击小 View
我今天尝试从 Obj-C 开始并转到 Swift,我正在阅读文档。我试图在 Swift 中创建一个简单的 IBOutlet,但它不断给我这些错误。 View Controller 没有初始化器 req
我正在尝试使用 VIM 完成(字典和当前缓冲区),但我遇到了问题?和 !在方法名称的末尾。我能以某种方式向 vim 解释方法名称(基本上是单词)最后只能有它,而且只有一个,即 method_name
我是一名优秀的程序员,十分优秀!