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;
}
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 NullPointerException
s, IllegalArgumentException
s 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With