假設我有一個拋出異常的自定義閱讀器對象:public StationReader { public StationReader(String inFile) throws FileNotFoundException { Scanner scan = new Scanner(inFile); while (scan.hasNextLine() { // blah blah blah } // Finish scanning scan.close(); }}我在另一個類 Tester 中調用 StationReader:public Tester { public static void main(String[] args) { try { StationReader sReader = new StationReader("i_hate_csv.csv"); } catch (FileNotFoundException e) { System.out.println("File not found arggghhhhhh"); } finally { // HOW TO CLOSE SCANNER HERE?? } }}現在讓我們想象一下,在掃描這些行時,拋出了一個異常,因此scan.close()永遠不會被調用。在這種情況下,如何關閉掃描儀對象?
1 回答

HUX布斯
TA貢獻1876條經驗 獲得超6個贊
在try-with-resources語句中編寫讀取過程,但不要捕獲任何異常,只需將它們傳遞回調用者即可,例如......
public class CustomReader {
public CustomReader(String inFile) throws FileNotFoundException {
try (Scanner scan = new Scanner(inFile)) {
while (scan.hasNextLine()) {
// blah blah blah
}
}
}
}
該try-with-resource語句會在代碼存在try塊時自動關閉資源
僅供參考:finally用于這個,但是當你有多個資源時,它變得凌亂。所有冰雹try-with-resources??
添加回答
舉報
0/150
提交
取消