Python – Catch Multiple Exceptions

Python always operates on an Exception based model. That is, any errors during the program execution are passed as Exceptions and returned to the programmer, which may be handled accordingly using Exception Handling techniques.

Sometimes, it is possible that a process raises more than one possible exception, depending on the flow of control. Thus, we may need to catch Multiple Exceptions for this program/function.

Let us understand how we can handle multiple exceptions in Python.


Catch Multiple Exceptions

Python allows us to handle multiple exceptions in 2 ways:

Using Multiple Except Blocks

We can catch multiple exceptions by sequentially writing down except blocks for all those exceptions.

The pseudo-code looks like this:

try:
    pass
except Exception1:
    pass
except Exception2:
    pass

Let us understand this way of handling through an example.

Consider the below function which tries to add all items of a List using the + operator, and also checks if any Integer item is less than 200. Since addition/concatenation can also fail if the types are different, there are multiple Exceptions possible.

input_list_1 = ['Hello', ' from', 123, 456, ' AskPython']
input_list_2 = [123, 456, ' AskPython']

def add_list(ip):
    # Adds all items of a list
    # Will raise ValueError if any integer item > 200
    # and will raise TypeError if addition operands are of different types
    if isinstance(ip, list):
        result = '' if isinstance(ip[0], str) else 0
        for item in ip:
            if isinstance(item, int) and item > 200:
                raise ValueError('Integer Item has to be <= 200')
            result = result + item
        return result
    else:
        return None

try:
    # Will raise TypeError
    res = add_list(input_list_1)
    print(res)
except TypeError as te:
    print(type(te), te)
except ValueError as ve:
    print(type(ve), ve)

try:
    # Will raise ValueError since 456 > 200
    res = add_list(input_list_2)
    print(res)
except TypeError as te:
    print(type(te), te)
except ValueError as ve:
    print(type(ve), ve)

The function is run on two lists, to show that multiple exceptions can be raised from a single function.

Output

<class 'TypeError'> can only concatenate str (not "int") to str
<class 'ValueError'> Integer Item has to be <= 200

Using a Single Except Block

We can also catch multiple exceptions in a single except block, if you want the same behavior for all those exceptions.

This can avoid unnecessary duplication of code and can save the programmer’s time if the output is the same for multiple exceptions.

Pseudo-code for the same:

try:
    pass
except (Exception1, Exception2) as e:
    pass

Let us modify the main block using a single except block for multiple exceptions.

try:
    res = add_list(input_list_1)
    print(res)
except (TypeError, ValueError) as err:
    print(type(err), err)

try:
    res = add_list(input_list_2)
    print(res)
except (TypeError, ValueError) as err:
    print(type(err), err)

The output will remain the same:

<class 'TypeError'> can only concatenate str (not "int") to str
<class 'ValueError'> Integer Item has to be <= 200

NOTE: The multiple exceptions can be any combination of in-built exceptions and custom exceptions.


Conclusion

In this article, we learned the two ways of handling multiple exceptions in Python, using multiple sequential except blocks, and also using a single except block to reduce duplication of code.


References

  • JournalDev article on Multiple Exception Handling