Skip to content

Python catch all exceptions

  • by

Use Try and except statements to catch all exceptions in Python. This can raise exceptions that are kept inside the try clause and that handle the exception are written inside except clause.

Python catch all exceptions

Simple example code try except block that catches all exceptions.

a = [1, 2, 3]
try:
    print("Second element = %d" % (a[1]))
    print("Fourth element = %d" % (a[3]))
except Exception as e:
    print("Error occurred")
    print(e)

Output:

Python catch all exceptions

Using Different Code Blocks for Multiple Exceptions

try:
    name = 'Bob'
    name += 5
except NameError as ne:
    # Code to handle NameError
    print(ne)
except TypeError as te:
    # Code to handle TypeError
    print(te)

Catch multiple exceptions in one line

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

Do comment if you have any doubts or suggestions on this Python exception topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading