英文:
What happens when try with resources throws an exception along with an exception when closing the resources automatically
问题
在try with resources块中发生异常的情况下,它将调用close方法来关闭资源。如果close方法也抛出异常,会发生什么?会抛出哪个异常?
英文:
Imagine a situation where, an exception occurs in try with resources block. It will call the close method to close the resources. What happens if close method also throws an exception. Which exception is thrown.?
答案1
得分: 3
答案是:两者都会被抛出!第一个异常稍微更突出一些。
首先,你的内部异常会被抛出。然后,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()
方法获取被抑制的异常。
英文:
The answer is: Both! The first one is just a bit more prominent.
First your inner exception will be thrown. Then the close() method of the Closeable will be called and if that one does also throw its exception, it will be suppressed by the first one. You can see that in the stack trace.
Test code:
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");
}
}
}
Console log:
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)
If you like to, you can get the suppressed exception with exception.getSuppressed()
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论