Member-only story
Stop Using Exceptions Like This in Python
Four common error-handling mistakes to avoid in Python
Imagine you are building a blogging app. In the normal flow of your blogging app, users are able to sign up and create blog posts.
An exception (error) is said to occur when the normal flow of your app is interrupted unexpectedly. For example, when a user signs up with an existing email on your blog site.
Exception handling means deciding what to do with this interruption as app developers. For instance, in this scenario, we could simply return an error message back to our users, write an error to our logging system, etc.
Error handling is an essential part of building any application, as it makes our code more maintainable.
To raise an exception in Python, we could simply do the following:
raise ValueError("Something has gone wrong.")
In this article, I intend to share with you some Python error-handling tips and some common bad practices to avoid.
TL;DR
- Never use bare
except
- Avoid catching or raising generic
Exception
- Refrain from just passing in
except
blocks
1. Avoid Bare except
The first rule of thumb is to absolutely avoid using bare except
, as it doesn't give us any exceptions object to inspect.
Furthermore, using bare except
also catches all exceptions, including exceptions that we generally don’t want, such as SystemExit
or KeyboardInterrupt
.
Here’s an example of using bare except
, which is not recommended:
So, what’s wrong with catching every exception?
Catching every exception could cause our application to fail without us really knowing why. This is a horrible idea when it comes to debugging.