Peter Bagnall
Peter Bagnall

Reputation: 1851

How specific should exception classes be?

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?

Upvotes: 5

Views: 273

Answers (2)

plast1K
plast1K

Reputation: 469

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.

try {}    catch (CryptographicException e)
{ ...doSomething }

catch (ArgumentOutOfBoundsException e)
{ ...doSomething }

catch (Exception e)
{ ...doSomething }

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.

Upvotes: 1

Sergey Stavichenko
Sergey Stavichenko

Reputation: 156

You must always extend the Exception class when you have difference logic to handle exception. Look for php Spl library, by the way it contains some exception classes, so you don't need to define your own.

Upvotes: 2

Related Questions