Member-only story

Catch All Exceptions in Python Without Breaking a Sweat

A Practical Guide to Handling Errors Like a Pro

Max N
3 min readMar 27, 2024
Photo by Nong on Unsplash

Dealing with exceptions is an integral part of writing robust and reliable Python code. While it’s always better to handle specific exceptions when possible, there may be times when you need to catch all exceptions in a single block.

In this article, we’ll explore how to do just that, along with some best practices to keep in mind.

The Basic Approach

The simplest way to catch all exceptions in Python is to use the bare except clause:

try:
# Some risky code here
result = 1 / 0
except:
# Handle all exceptions
print("Something went wrong!")

This will catch any exception raised within the try block. However, it's generally considered a bad practice because it can also catch exceptions that you didn't intend to catch, such as KeyboardInterrupt or SystemExit. It's better to be more specific about the exceptions you want to handle.

Catching All Standard Exceptions

To catch all standard exceptions (those derived from the base Exception class), you can use the following:

try:
# Some risky code here
result = 1 / 0
except…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet