這是確定的,但如果theBufferedWriter
你應該測試在關閉它之前不是空的。
你也可以這樣做:
BufferedWriter theBufferedWriter;
try {
theBufferedWriter = new ...
try {
...
} finally {
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
} catch (IOException anException) {
...
}
或:
BufferedWriter theBufferedWriter;
try {
theBufferedWriter = new ...
} catch (IOException createException) {
// do something with createException
return; // assuming we are in a method returning void
}
try {
...
} catch (IOException anException) {
...
// assuming we don't return here
}
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
但主要是我做這樣的操作在一個專用的方法(如寫入文件),喜歡扔/豁免,讓呼叫者可以處理(例如,要求其他文件,停止應用程序,...):
void someMethod(...) throws IOException {
BufferedWriter theBufferedWriter = new ...
try {
...
} catch (IOExcepption anException) {
try {
theBufferedWriter.close();
} catch (IOException closeException) {
closeException.printStackTrace();
// closeException is not thrown, anException represents the main/first problem
}
throw anException;
}
theBufferedWriter.close(); // throws the Exception, if any
}
請注意:英語不是我的冷杉噸也不是我的第二語言,任何幫助,將不勝感激
沒關係,但首先檢查null是更好的。 – qrtt1 2010-06-16 07:10:32
+1它不漂亮,但它必須完成 – 2010-06-16 08:38:40