How To Name Exceptions
Get ready for a wild ride—today, we are continuing our journey into Exception Management, a perplexing topic. My aim with this series of articles on exceptions is to clear up the confusion.
OK, let’s get into it.
How should we name our custom exceptions?
I follow these guidelines:
Name exceptions to communicate their error nature. Naming things in code is all about communication—about making what is happening in the program clear to other developers. ‘Other developers’ includes our future selves.
In this spirit, we want to communicate the error nature of our custom exceptions unambiguously.
This overarching rule can be further refined for concrete and abstract exceptions, respectively:
Omit the ‘Exception’ suffix on concrete exceptions. Specific exceptions exist for specific error scenarios. For example,
DuplicateCustomerException is unnecessarily long.
DuplicateCustomer is enough. Don’t believe me? Let’s see it in action:
throw new DuplicateCustomer();
It’s unambiguously pointing out an error—the customer already exists and is a duplicate.
Maintain the ‘Exception’ suffix on abstract Exception types. I know we have not yet covered abstract exceptions—we’ll get into these soon. In the meantime, consider them as exceptions for a range of errors, say, invalid input data. Following this rule, we could name an abstract exception concerned with invalid input data,
Without the ‘Exception’ suffix, we lose the error-nature of the exception.
InputDataException is clearly about error conditions; on the other hand, just
InputData is not.
That’s it! Well, almost.
There is one more guideline I like to follow when naming exceptions. When we violate this rule, it introduces an anti-pattern causing significant damage to a program. We’ll discover this rule and why its violation is an anti-pattern next time.