如何重写以下代码
try (A a = new A(); B b = new B()) {
//useful work here
}
catch (Exception e) {
//other code
}使用try-catch-finally构造?
如果我们只创建一个资源,那么有一个很好的链接here。
不幸的是,当我们创建多个资源时,我不明白如何概括这一点。
我不明白的一件事是,我们如何识别a发生了一些事情,而没有发生在'b‘上,反之亦然。
发布于 2017-12-25 08:44:24
没有一般规则,但您必须确保尝试关闭所有打开的资源,即使您不知道发生了什么以及在哪个资源中发生了什么。
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关闭时添加异常
https://stackoverflow.com/questions/47964866
复制相似问题