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:
You can catch all exceptions by using the Exception class in the except block, like this:
Catch all exceptions in Python
try:
# code that may raise an exception
except Exception:
# code to handle the exception
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
It's also possible to catch multiple types of exceptions by listing them as a tuple, like this:
Catch some specific exceptions in Python
try:
# code that may raise an exception
except (ExceptionType1, ExceptionType2):
# code to handle the exceptionIt'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:
Catch all exceptions in Python and give a name to that exception
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.