I can\'t seem to phrase this correctly for the search engine to pick up any meaningful results.
try{
BufferedReader reader = new BufferedReader( new File
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).
The difference is there could be other problems inside the code of your try block that could throw other types of Exception
s including subclasses of RuntimeException
(which don't have to be declared).
If you just catch Exception
, then you will catch all of those other errors too which may hide a different problem. Also your code inside the catch block can't assume the Exception happened due to an IOException since any kind of exception will be caught.
As a followup to dkatzel's answer, let's assume you start to read from the file in the same try block and the file tells you which value in a array of options to use:
String toPrint = {"Hi", "World", "I'm", "A", "String", "Array"};
try{
BufferedReader reader = new BufferedReader( new FileReader("foo.bar") );
String line = reader.readLine();
System.out.println(toPrint[Integer.parseInt(line)]);
}
catch(Exception e){
println( e.getMessage() );
}
Now you have absolutely no idea what really went wrong except through the stack trace. You can't handle any fixable problems. You can't tell in code whether the file doesn't exist (FileNotFoundException
), you don't have access to the file, (IOException
), if the first line wasn't an Integer (NumberFormatException
), or the number was bigger than the array length (ArrayIndexOutOfBoundsException
). If you wanted to print a default value if you couldn't read the number, you could instead catch a NumberFormatException
and print the value instead of having to quit the entire program.
I'll admit this is a pretty contrived example, but it should give you an explanation of why catching Exception
is bad. Marko also has a very good answer, stating that it usually is better to let the exception propagate up (especially with RuntimeException
s) than to create a bunch of messy code trying to deal with every single problem that can happen.