Best Practices for Exception Handling

Learn about the best practices that relate to exception handling in Python.

Here are some recommendations that relate to exceptions in Python.

Handling exceptions at the right level of abstraction

Exceptions are part of the principal functions that do one thing, and one thing only. The exception the function is handling (or raising) has to be consistent with the logic encapsulated on it.

In the code below, there's an example of what we mean by mixing different levels of abstractions. Imagine an object that acts as a transport for some data in our application. It connects to an external component where the data is going to be sent upon decoding. In the following listing, we will focus on the deliver_event method:

Get hands-on with 1200+ tech skills courses.