Do not catch “Generic exceptions types”

(Below scenario may be hypothetical, but for explanation purpose, let’s consider it happens…….)

Imagine you are using a service for achieving some task, for example, let’s say, you are buying something on an online shopping portal.

It so happens that while surfing for products, the site crashes. You contact the support and they tell you it was a “SYSTEM ERROR” and they will get it fixed. Such things happens and it’s ok for you. You move on.

After a few days, you are trying to purchase something on this website and while checking out, the site crashes in the 3rd party payment gateway. This time you are a little annoyed and you contact the support again and tell them your story. The support tells you it was a “SYSTEM ERROR” and they will get it fixed. You move on, since you cannot do anything about it besides trying again.

Time passes by and after a few days you successfully place an order with this site. You are excited about your product, it’s a new gift for your spouse. But this time the product goes to a different warehouse in a different city and the product does not reach you. You again contact the customer care, and they tell you again that it was a “SYSTEM ERROR” and they will get it fixed. This time you get furious. How could it be a “SYSTEM ERROR” every time something goes wrong? You want more details about the problem, you want to hear more about what went wrong. After all, you have invested your time, money and effort in this activity.

This is exactly how the consumer of our library would feel if we return them a generic exception type, every time something goes wrong.

The consumer of the code code expects more details to either fix the problem or get the problem fixed. Standard libraries such as .NET, precisely describe about each exception that can be expected from the calling code. If your API has business logic and you want to enforce certain things (for example validation), you can return your own exception types (by deriving from base) and communicate the same to the consumer of the API. In this way the consumer knows what to expect when and take necessary actions.

Exceptions should be handled on case-to-case basis. Catching generic exceptions is a code smell and has to be strictly avoided. They indicate negligence to detail. Microsoft does not recommend suppressing this rule. More details can be found on MSDN here.

Dattatraya Kale

Aspiring agile software craftsman, clean code, polyglot, in love with different programming paradigm. I am on a never-ending journey towards mastery of software.

Leave a Reply