Python Errors Done Right

An opinionated approach to structure your try-except code

Ilia Zaitsev
The Startup
Published in
5 min readJun 23, 2020

--

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.

Photo by Sarah Kilian on Unsplash

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.

if something_is_wrong():
raise Exception('error!')

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.

try:
function()
except ValueError:
process_value_error()
except AttributeError:
process_attribute_error()
...
except Exception: # everything non-specific gets there
failure()

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 ValueError or 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.

Include Traceback

Consider the following snippet. It catches the error and prints it to the standard output.

def some_complex_arithmetics(x, y)…

--

--

Ilia Zaitsev
The Startup

Software Developer & AI Enthusiast. Working with Machine Learning, Data Science, and Data Analytics. Writing posts every once in a while.