As a rule I try to avoid throwing instances of Exception, because this doesn’t convey much information about what went wrong.
But I’m finding that I’m getting a fair number of empty Exception classes, which look like this…
class DataNotFoundException extends Exception {
// just a tagging class
}
So functionally the class is identical to Exception. The only functional significance is I can now do this…
try {
... some code which throws exceptions ...
} catch (DataNotFoundException $dnfe) {
... do stuff ...
} catch (OtherException $oe) {
... do other stuff ...
}
My question is, where is the balance between having a huge number of tiny Exception classes and just throwing instances of Exception. Does anyone have any guidelines for when to introduce a new Exception class?
It’s not a bad practice to include lots of specific exceptions, but only ones relevant and reproduce able. If you choose to be very specific with them, it should go in a specific order, as well; going from very specific, to general.
This being attributed to the processing of events, and if a general Exception is first, all others will be skipped. Having specific exceptions before general ones will help in the idea that you acquire more information from them, as well.