How can I write a `try`/`except` block that catches all exceptions?
You can catch all exceptions by using the Exception
class in the except
block, like this:
try:
# code that may raise an exception
except Exception:
# code to handle the exception
Watch a video course
Python - The Practical Guide
It's also possible to catch multiple types of exceptions by listing them as a tuple, like this:
try:
# code that may raise an exception
except (ExceptionType1, ExceptionType2):
# code to handle the exception
It's generally not recommended to use a bare except clause, since it will also catch unexpected and unintended exceptions, such as SystemExit
and KeyboardInterrupt
, which would make it difficult to debug and terminate the program.
You can also add the keyword as
to the except clause to give a name to the exception, in order to access the exception instance, like this:
try:
# code that may raise an exception
except Exception as e:
# code to handle the exception
print(e)
It's a best practice to catch only the specific exception types that you expect to be raised and handle them appropriately.