是否有治療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