当自动关闭资源时尝试使用资源引发异常以及异常时会发生啥

Posted

技术标签:

【中文标题】当自动关闭资源时尝试使用资源引发异常以及异常时会发生啥【英文标题】:What happens when try with resources throws an exception along with an exception when closing the resources automatically当自动关闭资源时尝试使用资源引发异常以及异常时会发生什么 【发布时间】:2020-10-09 05:52:04 【问题描述】:

想象一下,try with resources 块中发生异常的情况。它将调用 close 方法来关闭资源。如果 close 方法也抛出异常会发生什么。抛出哪个异常?

【问题讨论】:

It’s all in the manual。甚至您在问题中使用的the tag info of [try-with-resources] 也解释了它...... 【参考方案1】:

答案是:两者都有!第一个稍微突出一点。

首先你的内部异常会被抛出。然后将调用 Closeable 的 close() 方法,如果该方法也抛出异常,它将被第一个方法抑制。您可以在堆栈跟踪中看到这一点。

测试代码:

public class DemoApplication 

    public static void main(String[] args) throws IOException 

        try (Test test = new Test()) 
            throw new RuntimeException("RuntimeException");
        
    

    private static class Test implements Closeable 
        @Override
        public void close() throws IOException 
            throw new IOException("IOException");
        
    

控制台日志:

Exception in thread "main" java.lang.RuntimeException: RuntimeException
    at DemoApplication.main(DemoApplication.java:15)
    Suppressed: java.io.IOException: IOException
        at DemoApplication$Test.close(DemoApplication.java:22)
        at DemoApplication.main(DemoApplication.java:16)

如果您愿意,可以使用exception.getSuppressed() 获得抑制的异常。

【讨论】:

您的描述弄错了,它是 second 异常(即由close 操作引发的异常)将被抑制。如堆栈跟踪所示! 给出的描述是对的,据说close方法抛出的异常被抑制了。

以上是关于当自动关闭资源时尝试使用资源引发异常以及异常时会发生啥的主要内容,如果未能解决你的问题,请参考以下文章