Member-only story
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…