【发布时间】:2018-11-05 05:56:17
【问题描述】:
我知道引入 try-with-resources 语句是为了解决(或)防止异常屏蔽。
考虑以下代码:
class TestExceptionSuppressing {
public static void main(String[] args) {
try {
testMethod();
} catch (Exception e) {
System.out.println(e.getMessage());
for (Throwable t : e.getSuppressed()) {
System.err.println("Suppressed Exceptions List: " + t);
}
}
}
static void testMethod() {
try (InnerClass inner = new InnerClass()) {
throw new IOException("Exception thrown within try block");
} catch (Exception e) {
throw new RuntimeException(
"Exception thrown within catch block.Hence exception thrown within try block will be lost (or) masked");
}
}
static class InnerClass implements AutoCloseable {
@Override
public void close() throws Exception {
throw new Exception("Exception thrown in close method will be tacked on to existing exceptions");
}
}
}
输出:在 catch 块中抛出异常。因此在 try 块中抛出的异常将丢失(或)被屏蔽
显然,testMethod() 的 catch 块中抛出的异常已经掩盖了 try 块中抛出的 io 异常以及被抑制并添加到此 io 异常中的异常(在 close 方法中抛出)
此代码示例可能证明 try-with-resources 可能无法完全防止异常屏蔽。
我知道这里的情况很混乱,可能会让人感到困惑,但有可能发生这种情况。 我的问题是,有没有办法防止这种情况发生,即即使使用 try-with-resources 语句仍然会发生异常屏蔽?
【问题讨论】:
-
这是与 try with resource 同时引入的更改,但是一个普通的 try/finally 块允许您查看被抑制的异常。
标签: java exception try-with-resources