This is done to allow more cleaner and more precise catching of exceptions. If all of your code just throws Exception
, your exception-handling code will have to look like this:
try {
// ...
throw new Exception("configuration error");
// ...
throw new Exception("missing value error");
// etc.
} catch (Exception e) {
// do something
}
And it will be awkward at the least to handle different kinds of errors in different ways. More importantly, this code will swallow all exceptions, even ones you weren't expecting and for which you haven't written specific error-handling logic. On the other hand, if you write
try {
// ...
throw new ConfigurationException();
// ...
throw new MissingValueException();
// etc.
} catch (ConfigurationException e) {
System.err.println("error: bad configuration");
System.exit(1);
} catch (MissingValueException e) {
return DEFAULT_VALUE;
}
you'll be able to easily and cleanly handle different kinds of errors, and won't have to worry that your error handling code will be run in situations that you didn't expect it to.