Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use IOexception instead of Exception when catching?

Tags:

java

exception

I can't seem to phrase this correctly for the search engine to pick up any meaningful results.

try{
    BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
}
catch(Exception e){
    println( e.getMessage() );
}

So FileReader only throws the FileNotFoundException, which as I understand it is an IOException, which is an Exception. Can someone explain why I would catch FileNotFoundException or IOException instead of just specifying the generic "Exception" and not having to import an exception (i.e. import java.io.FileNotFoundException;)? Is it strictly for readability?

I've caught the exception using all three names and I can't find a difference.

EDIT:--------------------

private BufferedReader askUserForFile(String prompt){
        BufferedReader rd = null;
        while(rd == null){
            try{
                String filename = readLine(prompt);
                rd = new BufferedReader( new FileReader(filename) );
            }
            catch(Exception e){
                println(e.getMessage());
            }
        }
        return rd;
    }
like image 825
patterned Avatar asked Dec 17 '13 21:12

patterned


1 Answers

Exception is the mother of all exceptions, including all RuntimeException subclasses. When you specify to catch it, you'll get much more fish in the net than you wanted, like NullPointerExceptions, IllegalArgumentExceptions and so on.

While catching the generic Exception is the right thing to do at some point in your code, catching it at any lower layer is almost certainly wrong and can hurt the behavior of your application.

The more important skill to learn in Java is not how to catch exceptions, but how to not catch them, instead letting them propagate up the call stack, towards the exception barrier, the one common spot in the code where all errors are caught and uniformly handled (typically by logging, rolling back the transaction, and similar).

like image 62
Marko Topolnik Avatar answered Sep 19 '22 22:09

Marko Topolnik