嵌套的尝试捕获块未捕获异常

问题描述 投票:0回答:2

我的程序正在尝试浏览我的目录,以查找是否存在.cmp或.txt文件。

如果fileName等于“ test”,并且既不存在test.cmp文件也不存在test.txt文件,尽管我的try-catch块位于第一个catch之下,但我的程序仍将抛出FileNotFoundException。我尝试过移动第二个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”不存在。

java exception try-catch filenotfoundexception
2个回答
1
投票

由于此行,正在打印该异常:

e2.printStackTrace();

它正在按您的期望工作,只是打印出它得到的错误。如果您不想看到这些printStackTrace()呼叫,可以将其删除。好吧,不要删除最后一个catch块中的那个,否则您将永远不知道那里是否有问题。

另外,此设计完全基于异常,不建议这样做。我是sure,在File类中有一些方法来检查文件的存在。


0
投票

此程序正在按预期方式工作...

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

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

}

以上catch子句捕获您的IOException并用e2.printStackTrace();打印它>

© www.soinside.com 2019 - 2024. All rights reserved.