Java編程思想第十二章練習23

習題答案是沒有加粗的刪除部分;用不用加上?

加上後,nc1在1/0拋異常時就釋放了資源,還是說因爲在構造方法中,構造方法失敗,FailingConstructor23b 對象不存在,就談不上釋放FailingConstructor23b中的nc1資源

public class FailingConstructor23b {
private BufferedReader in;
NeedsCleanup nc1;
NeedsCleanup nc2;
public FailingConstructor23b(String fname) throws Exception {
nc1 = new NeedsCleanup();
try {
in = new BufferedReader(new FileReader(fname));
//code might throw exceptions
int a = 1/0;
} catch(FileNotFoundException e) {
System.out.println("Could not find file " + fname);
nc1.dispose()
throw e;
} catch(Exception e) {
try {
in.close();
nc1.dispose()
} catch(IOException e2) {
System.out.println(“in.close() failed”);
}
throw e;
}
nc2 = new NeedsCleanup();
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章