How to name exceptions? It’s not so obvious…

Naming things is one of the most difficult things in our job. Naming exceptions are even more complicated because exceptions are not regular classes. In this article, I’ll tell you a bit about naming conventions I’ve found and tell pros and cons of them.

The ‘Exception’ suffix. To add or not to add

Leaving without the suffix

Of course, in languages like c++ you can throw anything. For example, you can throw a null (BTW, it will be cast to long in this case).

The world with the ‘Exception’ suffix

It may be confusing. You have two classes with the same name (in different namespaces, of course) but one of them is an exception, the second isn’t. I know you can see the folder where the class is placed. If it’s in folderexception it’s probably an exception. The suffix will make it more clear. In a small project it’s not so huge problem but in a large one, it might be.

The naming

It’s a reason why the exception should be a noun and should describe exactly what happened. A more clear exception would be ArgumentCannotBeNull or ProductIsOutOfStock. Thanks to it when you take a look at the try-catchstatement you know exactly what errors may occur.

On the other hand, you’ll have to create a new class for every unwanted behavior. It can be really a large number of new classes! Imagine that a class can throw 10 exceptions. How will the catch section look like? In many cases, you’ll deal with the exception the same way. It’s not only redundant but you have to duplicate your code.

To solve it you can create a more generic class like InvalidArgumentException with a custom message. The message will tell you more about the problem and it can be more dynamic for example ‘A product with SKU “how-to-handle-fame” is out of stock’. It’s much handier than an exception ProductIsOutOfStock(“how-to-handle-fame”).


Please let me know if you have any other thoughts about exceptions, please let us know in the comments section.

Originally published at Developer 2.0.

I'M a backend engineer, blogger, speaker and open-source developer :)