来自 try 块和 try-with-resources 的异常

Exceptions from both try block and try-with-resources

Documentation

However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

粗体部分没看懂

... if exceptions are thrown from both the try block and the try-with-resources statement ...

如何从 try-with-resources 语句和 try 块中抛出异常?如果try-with-resources语句抛出异常,说明资源初始化失败。在这种情况下,try 块永远不会执行。因此前面的说法不可能发生。

我一定是误解了这个 documentation 以及 try-with-resources 的工作原理。您能否提供粗体声明实际发生的示例?


提到的方法
static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

How can an exception be thrown from both the try-with-resources statement and the try block ? If the exception is thrown from the try-with-resources statement, it means that resource initialization failed.

try-with-resources语句不仅会初始化还会关闭资源,关闭可能会抛出异常

这句话紧接在描述使用try-finally时的类似情况之后,并与try-with-resources[=进行比较19=].