簡體   English   中英

嵌套 Try-Catch 塊未捕獲異常

[英]Nested Try-Catch Block Not Catching Exception

我的程序正在嘗試掃描我的目錄以搜索是否存在 .cmp 或 .txt 文件。

如果 fileName 等於“test”並且 test.cmp 和 test.txt 文件都不存在,我的程序仍然會拋出 FileNotFoundException,盡管我的 try-catch 塊在第一個捕獲下。 我嘗試移動第二個 try-catch 塊,但似乎沒有任何效果——我用一個不存在的文件測試代碼的所有內容最終都會引發異常。

public int checkFileExistence() {
        BufferedReader br = null;
        int whichFileExists = 0;


        try {//check to see if a .cmp exists
            br = new BufferedReader(new FileReader(fileName + ".cmp")); 
            whichFileExists = 0;// a .cmp exists
        }

        catch (IOException e){ //runs if a .cmp file has not been found
            try {//check to see if a .txt file exists
                br = new BufferedReader(new FileReader(fileName + ".txt"));
                whichFileExists = 1;//a .txt file exists
            }
            catch (IOException e2) {//if no .txt (and .cmp) file was found  

                e2.printStackTrace();
                whichFileExists = 2; //no file exists

            }

        }

        finally {   

            try {
                br.close();
            } 

            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }


        return whichFileExists;
    }


我希望程序能夠工作,但是每次我測試程序時,程序都會拋出一個 FileNotFoundException,它說“test.txt”不存在。

由於這一行,它正在打印該異常:

e2.printStackTrace();

它按您的預期工作,只是打印它得到的錯誤。 如果您不想看到它們,可以刪除這些printStackTrace()調用。 好吧,不要刪除最后一個 catch 塊中的那個,否則你永遠不會知道那里是否有問題。

另外需要說明的是,這種設計完全基於異常,不推薦。 確定File class 中有一些方法可以檢查文件是否存在。

該程序按預期工作...

catch (IOException e2) {//if no .txt (and .cmp) file was found  

    e2.printStackTrace();
    whichFileExists = 2; //no file exists

}

上面的 catch 子句捕獲您的 IOException 並使用e2.printStackTrace();打印它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM