【发布时间】:2011-02-11 13:19:34
【问题描述】:
是否有一种不那么丑陋的方式来处理close() 异常以关闭两个流:
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
try {
copy(in, out);
} finally {
try {
in.close();
} catch (Exception e) {
try {
// event if in.close fails, need to close the out
out.close();
} catch (Exception e2) {}
throw e; // and throw the 'in' exception
}
}
out.close();
}
更新:以上所有代码都在一个 try-catch 中,感谢您的警告。
终于(在答案之后):
使用Execute Around idiom 可以完成一个很好的实用方法(感谢 Tom Hawtin)。
【问题讨论】:
-
考虑在适当的抽象级别捕获异常,例如IOException等,而不是过于模糊的Exception。
-
我认为对于这种情况,抛出哪个异常无关紧要。或者为什么会?
-
请注意,您的代码不一定关闭
in,见stackoverflow.com/questions/2441853/…