如何重写以下代码
try (A a = new A(); B b = new B()) {
//useful work here
}
catch (Exception e) {
//other code
}
使用 try-catch-finally 结构?
如果我们只创建一个资源,那么有一个很好的链接 here .
不幸的是,我不明白当我们创建多个资源时如何概括这一点。
我不明白的一件事是我们如何识别发生在 a
上而没有发生在 'b' 上的事情,反之亦然。
最佳答案
没有通用规则,但您必须确保尝试关闭打开的所有资源,即使不知道发生了什么以及在哪个资源中。
void test() throws Exception {
A a = null;
B b = null;
Exception myException = null;
try {
a = new A();
b = new B();
//useful work here
} catch (Exception e) {
myException = e;
throw e;
} finally {
Throwable tA = handleCloaseable(a);
Throwable tB = handleCloaseable(b);
boolean throwIt = false;
if (myException == null && tA != null || tB != null) {
myException = new Exception();
throwIt = true;
}
if (tA != null) {
myException.addSuppressed(tA);
}
if (tB != null) {
myException.addSuppressed(tB);
}
if (throwIt) {
throw myException;
}
}
}
Throwable handleCloaseable(AutoCloseable e){ // your resources must implements AutoCloseable or Closeable
if (e != null) {
try {
e.close();
} catch (Throwable t) {
return t;
}
}
return null;
}
如果在尝试关闭资源时发生任何异常,则创建新的Exception
(如果不存在),并添加尝试使用addSuppressed
关闭时出现的异常
关于java - 如何仅使用 try-catch-finally 构造重写具有两个资源的 try-with-resources?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964866/