如何在 try-with-resource 语句中捕获 close 方法抛出的异常

How to catch exception thrown by close method in try-with-resource statement

我正在阅读 Java 中的 try-with-resource 语句,该语句可用于指定任意数量的资源。

try (Resource1 res1 = initialize_code; Resource1 res2 = initialize_code; ...) 
{
    statement;
}

现在,当 try 块退出时(正常或异常抛出异常),将调用所有资源对象的 close 方法。但是一些 close 方法可以抛出异常。如果 close 本身抛出异常,在那种情况下会发生什么?

But some close methods can throw exceptions.

是的,他们可以,你是对的。此外,资源以其初始化的相反顺序关闭。

What will happen if close method itself throws exception?

正如您提到的,某些 close 方法也可能引发异常。如果在正常执行 try 块时发生这种情况,则将异常抛给调用者。

但是当另一个异常被抛出时,导致 close 要调用的资源的方法,并且 close 方法之一抛出异常(实际上是重要性较低的异常)?

在这种情况下,原始异常被重新抛出,而异常是由 close 方法引起的 也被捕获并附加为 supressed exception。这实际上是使用 try-with-resource 的优势之一,因为手动实现这种机制会很乏味。

try {
 ///statements.
} catch (IOException e) { 
   Throwable[] supressedExceptions = ex.getSupressed();
}