HACKER Q&A
📣 behnamoh

Why catching specific exceptions is better?


Why do people recommend catching each type of exception separately? This takes a lot of time because we have to dig deep into the library code we're using to consider all the different ways functions - and any functions in their dependencies hierarchy - would throw exceptions.


  👤 kevg123 Accepted Answer ✓
The more common recommendation is to catch what you need to handle in a special way (if any) and then have a catch-all (or re-throw) for the rest, and if you don't need to catch anything specific, then just catch (or re-throw) all.

Think of exceptions like error codes. Most often one just checks if there is an error or not. Sometimes, one checks for specific error codes in addition to the general check. It would be rare to check every single error code, though possible.

By this analogy, I think the recommendation to check each type of exception is very uncommon.

Most importantly, make sure you do always catch exceptions at some level and handle them somehow (even if it's just logging), and also make sure no exception/error information is lost (e.g. blank catch block, not logging all exception details, not re-throwing with an inner exception so the original stack is lost, etc.).


👤 caprock
There are two things which helped me understand this better.

1. Exception handling is a form of flow control

Once you understand exceptions are a normal part of program flow, you begin to see how they fit into the broader logic. They help encapsulate and guide handling of common error cases.

2. There's no need to be over-granular

It's not necessary to go overboard and capture every single possible exception. You can explicitly capture the most common exceptions, log them, and handle/cleanup appropriately. Then you can have a fallback global trap to log and catch any others. If you start to see something unexpected a lot, then you can add an explicit handler for it if needed. It's mostly just about having specific cleanup and good logging for awareness of runtime issues.


👤 behnamoh
I should add that even Python's standard lib has functions that throw exceptions. This behavior is not immediately visible in the function type signature (`-> str` doesn't tell us that the function could return string or throw). So essentially the programmer needs to read the function body and look for exceptions.

Also, when handling each type of exception, that often means we need to import those specific exceptions. Importing tens of exceptions at the top of the file is just not an elegant approach imo. Also, we can never be sure that we've found all types of exceptions.