Blog |

How to Catch Multiple Exceptions in Python

How to Catch Multiple Exceptions in Python
Table of Contents

When a program encounters an exception during execution, it is terminated if the exception is not handled. By handling multiple exceptions, a program can respond to different exceptions without terminating it.

In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.

There are several approaches for handling multiple exceptions in Python, the most common of which are discussed below.


Using Same Code Block for Multiple Exceptions

With this approach, the same code block is executed if any of the listed exceptions occurs. Here's an example:

    name = 'Bob'
    name += 5
except (NameError, TypeError) as error:

In the above example, the code in the except block will be executed if any of the listed exceptions occurs. Running the above code raises a TypeError, which is handled by the code, producing the following output:

cannot concatenate 'str' and 'int' objects


Using Different Code Blocks for Multiple Exceptions

If some exceptions need to be handled differently, they can be placed in their own except clause:

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

In the above example, NameError and TypeError are two possible exceptions in the code, which are handled differently in their own except blocks.


Investigating Exceptions using If, Elif, Else Statements

Exceptions can also be checked using if-elif-else conditions, which can be useful if the exception needs to be investigated further:

import errno

    f = open('/opt/tmp/myfile.txt')
except IOError as e:
    if e.errno == errno.ENOENT:
        print('File not found')
    elif e.errno == errno.EACCES:
        print('Permission denied')
        print e

Here, the variable e holds an instance of the raised IOError. The additional status code of the exception is checked in the if, elif and else blocks and the first match is executed:

File not found


Multiple Except Clauses Matching

There may be cases where a piece of code causes an exception that can match multiple except clauses:

    f = open('/opt/tmp/myfile.txt')
except EnvironmentError:
    print('Failed to open file')
except IOError:
    print('File not found')

Since EnvironmentError is more general than IOError, it matches the exception in the code above. The EnvironmentError except clause is listed first, so the code within it gets executed, producing the following output:

Failed to open file


Track, Analyze and Manage Errors with Rollbar

Managing Multiple Errors/Exceptions in your Python code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python Errors easier than ever. Sign Up Today!

Related Posts

See all posts

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Start continuously improving your code today.

Get Started Shape