是否有治疗close()
例外,关闭两个流,那么的不那么丑陋的方式:的Java IO丑陋的try-finally块
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();
}
更新:所有上面的代码是一个尝试,渔获物中,由于为警告。
FINALLY(后回答):
,并可以使用Execute Around idiom(感谢汤姆Hawtin)做一个很好的实用方法。
考虑在抽象的适当水平捕获异常,例如IOException等,而不是过于模糊的异常。 – JRL 2010-04-23 14:20:02
我认为对于这种情况,抛出哪个异常无关紧要。或者为什么会呢? – 2010-04-23 17:02:09
请注意,您的代码不一定关闭'in',请参阅http://stackoverflow.com/questions/2441853/java-resource-management-please-help-to-understand-findbugs-results – meriton 2010-04-27 21:11:51