想象一下 MyOpenedFile 是用打开的流包装文件的东西。然后假设这段代码:
// method in an Util class
static void safeClose(MyOpenedFile f) {
if (f != null) {
try {
f.close();
} catch(IOException ex) { /* add logging or console output */ }
}
}
问题的实际方法:
void doSomeFileOperation(...) throws IOException, ... {
MyOpenedFile f1 = null;
MyOpenedFile f2 = null;
try {
/* method's "business logic" code beings */
f1 = new MyOpenedFile(...);
//do stuff
f2 = new MyOpenedFile(...);
// do stuff
f1.close(); f1 = null;
// do stuff with f1 closed
f2.close(); f2 = null;
// do stuff with f2 closed
/* method's "business logic" code ends */
} finally {
Util.safeClose(f1); f1 = null;
Util.safeClose(f2); f2 = null;
}
}
现在这很混乱,特别容易出错(例如,finally 块中的某些代码可能很难在单元测试中调用)。例如,在 C++ 中,析构函数会负责清理(由作用域指针析构函数调用或直接调用),代码会更干净。
那么,是否有更好/更好/更清洁的方法来包装上面的业务逻辑代码,以便传播任何异常但两个文件都f1
被f2
关闭(或者至少在两者上都尝试关闭,即使它失败了)?
还可以提供指向任何开源库(例如 Apache Commons)的答案,欢迎提供漂亮的包装器。