Python Errors Done Right
An opinionated approach to structure your try-except code
Exceptions mechanism is widely adopted among modern programming languages, and Python is not an exception. (Pun intended!) Though this topic could seem obvious, like wrap your code blocks with try-catch clauses, and that’s all, there are some minor but important details, and taking them into account should make your code a bit cleaner.
In this post, I’m going through some guidelines on how to structure error processing in Python that I derived from my personal experience.
Use Meaningful Classes
It is very tempting to write the following code, and I’ve seen it several times in projects where I was a collaborator.
It is better to use a more specific exception class instead. It sounds like common wisdom, but still, every once in a while, you can see this approach of raising the most generic exception instead of being specific.
Of course, the first reason to use more specific exceptions is to make possible writing multi-branch error handlers as the following snippet shows.
except Exception: # everything non-specific gets there
The second reason is more of a semantical point of view. The generic exception class doesn’t give you any hint into what went wrong. If you pick
TypeError instead, it immediately gives a bit more informative feedback to the reader even before reading the error message itself.
In case if your package includes some complex logic and many sub-modules, you could even inherit from the base class to create a dedicated error with some additional functionality or information. In most cases, however, it is perfectly fine to go with built-in types, and even some large and complex Python libraries do so.
Consider the following snippet. It catches the error and prints it to the standard output.
def some_complex_arithmetics(x, y)…