eShopOnWeb Architecture (3/16) – uses custom exceptions to more explicitly express what has gone wrong

In the ApplicationCore project eShopOnWeb defines some custom exceptions

This approach means we can raise strongly typed exceptions rather than throwing an InvalidOperationException (for example) with its string message property set. This in itself however isn’t a huge reason to use custom exceptions but

if we need to do something when we have an empty basket during checkout (for example) we can catch EmptyBasketOnCheckoutException rather than catching InvalidOperationException and string matching on its message property…

BUT… Microsofts Best Practices for exceptions page recommends we only introduce new exceptions classes when predefined ones don’t apply

I guess what ‘doesn’t apply’ means is open to interpretation. For example can we consider trying to create an order for empty basket an invalid operation.. almost certainly yes.

What do you think? Do you regularly define custom exceptions or use built in ones where possible? IMHO throwing pre-defined exceptions is fine until we need to explicitly handle certain error scenarios differently than others. In this case I’d favour custom exceptions to avoid messy string matching in catch blocks.

Leave a Reply

Your email address will not be published. Required fields are marked *