亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在封閉類之外調用掃描儀對象時如何關閉它?

在封閉類之外調用掃描儀對象時如何關閉它?

郎朗坤 2021-12-30 16:15:34
假設我有一個拋出異常的自定義閱讀器對象: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??


查看完整回答
反對 回復 2021-12-30
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號