如何捕获try-with-resource语句中close方法引发的异常 [英] How to catch exception thrown by close method in try-with-resource statement

查看:56
本文介绍了如何捕获try-with-resource语句中close方法引发的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was reading about try-with-resource statement in Java which can be used to specify any number of resources.

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

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

Now when the try block exits (normally or abnormally throwing an exception) the close methods of all resource objects are invoked. But some close methods can throw exceptions. What will happen in that scenario if close itself throws exception?

推荐答案

但是某些关闭方法可能会引发异常.

But some close methods can throw exceptions.

是的,他们可以,而您是对的.同样,资源以其初始化的相反顺序关闭.

Yes they can and you are right. Also the resources are closed in reverse order of their initialization.

如果 close 方法本身抛出异常,将会发生什么?

What will happen if close method itself throws exception?

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

As you mentioned some close methods can also throw exceptions. If that happens when try block is executed normally then the exception is thrown to caller.

但是当引发另一个异常导致 close 时该怎么办?调用资源的方法,而 close 方法之一引发异常(实际上是重要性较低的异常)?

But what when another exception had been thrown, causing close methods of the resources to be called, and one of the close method throws an exception (exception of lower importance actually)?

在这种情况下,原始异常将被重新抛出,并且由 close 方法引起的异常也被捕获并附加为禁止的异常.实际上,这是使用try-with-resource的优势之一,因为实现这种机制手工操作很繁琐.

In this situation original exception gets rethrown and the exceptions caused by close method are also caught and attached as supressed exception. This is actually one of the advantge using try-with-resource becuase implementing such mechanism would be tedious to implement by hand.

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

这篇关于如何捕获try-with-resource语句中close方法引发的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆