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

时间:2019-10-09 04:24:05

标签: java exception try-catch filenotfoundexception

我的程序正在尝试浏览我的目录,以查找是否存在.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”不存在。

2 个答案:

答案 0 :(得分:4)

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

e2.printStackTrace();

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

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

答案 1 :(得分:1)

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

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

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

}

上面的catch子句捕获您的IOException并使用e2.printStackTrace();

打印它