简体   繁体   中英

Nested Try-Catch Block Not Catching Exception

My program is attempting to scan through my directory in search of the existence of.cmp or.txt files.

If fileName were to equal "test" and if neither test.cmp nor test.txt files existed, my program would still throw a FileNotFoundException despite my try-catch block under the first catch. I've tried moving the second try-catch block around, but nothing seems to work – everything I test the code out with a file that doesn't exist still ends up throwing an exception.

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;
    }


I would expect the program to work, but each time I test the program, the program throws a FileNotFoundException where it says "test.txt" doesn't exist.

It is printing that exception because of this line:

e2.printStackTrace();

It's working as you are expecting, just printing the error it got. You can remove these printStackTrace() calls if you don't want to see them. Well, don't remove the one in the last catch block, otherwise you would never know if there is a problem there.

On a separate note, this design is totally based on exceptions, which is not recommended. I'm sure there are methods in the File class to check for existence of files.

This program is working as expected...

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

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

}

Above catch clause catches your IOException and prints it with e2.printStackTrace();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM