Design Patterns – Is It Good Practice to Use Self-Defined Exceptions?

Architecturedesign-patternsexceptions

Our team has different opinions about the practice of using self-defined exception for handling the business logic.

Someone says it is good as the exception comes meaningful and readable, and the opposition thinks it is redundant to define every possible exception and catching exceptions is performance hurting.

Would you share your thoughts and experience?

Best Answer

Like many things in programming, using custom exceptions is good if done for the right reasons and in the right situations.

If a built-in exception can acurrately describe the situation at hand, use it. E.g. FileNotFoundException, TimeoutException, KeyNotFoundException, etc.

If non of the built-in exception classes describe the situation, then you should make your own. If custom exceptions were bad, the built-in classes would be sealed or final or similar. However, don't go nuts. Just like with classes, a given exception type should probably be thrown from more than one place, otherwise it is likely unnecessarily specific.

However, a better rule of the thumb for whether to have custom exceptions is to consider what the caller will do about it when the exception gets thrown. If you have three erroneous situations that are handled in three very different ways, it makes sense to have three types because then the caller can have three catch blocks accordingly. The alternative, which is to inspect the message or data to decide what to do, is more complicated and thus more prone to error.

If all three situations instead are handled identically, it may not be worth the hassle of additional types, when just using the exception message should be enough to diagnose what the situation is. I've had to deal with many situations where a function can throw a dozen different exception types, but that to me as the caller, have inconsequential differences, so laziness kicks in and I just catch {} without the exception type and feel a little guilty about it. Don't cause that to happen.

As for one of the claims you wrote:

catching exceptions is performance hurting.

While that is true, there is virtually no difference between having custom exceptions that are caught and thrown vs just using ApplicationException for everything and making decisions based on the exception message. However, the for former situation, it is considerably easier for us humans to reason about what is happening during program execution.

Related Topic