Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching java exceptions FileNotFound and IOException at the same time

Is the FileNotFoundException somehow a "sub-exception" of the IOException?

This is my code opening an input stream to a file at the given path:

   method(){
        FileInputStream fs;
        try {
            fs = new FileInputStream(path);
            //
            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

How come I can neglect the FileNotFound and just catch the IOException instead? Is the FNFException a part of the IOException?

Instead of catching the exceptions, what if I throw an IOException in my method?

    method() throws IOException{

        FileInputStream fs;
        fs = new FileInputStream(path);
        //
        fs.close();

    }

Can I proceed to catch a FileNotFoundException at the invoking method like this?

    try {

         method();

    }catch (FileNotFoundException e1) {}

Thanks for any help you might be able to provide!

like image 995
xrdty Avatar asked Mar 05 '14 11:03

xrdty


1 Answers

Yes, it is.

If you look at inheritance FileNotFoundException is a sub-class of IOException. By catching the super class you also catch anything that extends it.

You can catch the more specific one first as in your first example if you need to handle it differently.

like image 147
Tim B Avatar answered Sep 28 '22 16:09

Tim B