How specific should exception classes be?

As a rule, I try not to throw Exception instances because this does not convey much information about what went wrong.

But I found that I am getting quite a few empty Exception classes that look like this:

class DataNotFoundException extends Exception { // just a tagging class } 

Thus, the functionally class is identical to Exception. The only functional value - now I can do it ...

 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 Exception instances. Does anyone have any recommendations as to when to introduce a new Exception class?

+4
source share
2 answers

Good practice includes many specific exceptions, but only relevant and reproducible. If you decide to be very specific with them, he must also go in a certain order; from very specific to general.

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

This is related to event handling, and if the first exception is the first, all others will be skipped. Special exceptions to general ones can help in the fact that you also get more information from them.

+1
source

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

+2
source

All Articles