How to Catch Multiple Exceptions in Python?

Catching Multiple Exceptions Individually

If you wish to have different handlers for each type of exception, then you could catch them individually like so:

try:
    # ...
except ValueError:
    pass
except AssertionError:
    pass

You could get the exception as a variable using the as clause in Python 2.6+:

# Python 2.6+

try:
    # ...
except ValueError as err:
    print(err)

And in Python 2.5 and below, you would separate the exception and the variable name using a comma (instead of as). For example:

# Python 2.5 and below

try:
    # ...
except ValueError, err:
    print(err)

Catching Multiple Exceptions in One Line

If you want to specify the same handler for multiple exceptions, then you can parenthesize them in a tuple and do the following:

# Python 2.6+

try:
    # ...
except (ValueError, AssertionError) as e:
    print(e)

For Python 2.5 and below, the syntax is slightly different, in that the exceptions must be separated from the variable with a comma (instead of as). For example:

# Python 2.5 and below

try:
    # ...
except (ValueError, AssertionError), e:
    print(e)

Important thing to note here is that in either syntax, when catching multiple exceptions in the except clause, the parentheses around the exceptions are required. The reason for this is because the older syntax of Python used a comma (instead of as) to separate the exceptions from the variable name, and since multiple exceptions are separated by a comma too, it can lead to unintended results.

Reusing:

If you want to reuse the same exceptions in multiple places in your code, you could consider a pre-defined tuple like so:

InvalidInputErrors = (ValueError, AssertionError);

try:
    # ...
except InvalidInputErrors as e:
    print(e)

Using Multiple & Single Exceptions Together:

You can, of course, also mix and match multiple exceptions and singular ones under the same try block. For example:

try:
    # ...
except (ValueError, AssertionError):
    pass
except RuntimeError:
    pass

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.