Catch multiple exceptions in one except block in Python

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Catch multiple exceptions in one except block in Python #

Use a parenthesized tuple to catch multiple exceptions in one except block, e.g. except (IndexError, ZeroDivisionError) as e:. You can specify as many exception classes between the parentheses and the except block will run if the try block raises one of the specified exceptions.

main.py
my_list = [] try: print(my_list[1000]) except (IndexError, ZeroDivisionError) as e: # 👇️ this runs pass

We used a parenthesized tuple to catch multiple exceptions in a single except block.

The except block in the example will run if the try block raises an IndexError or a ZeroDivisionError.

If you have to specify multiple exception classes on a single line, make sure to wrap them in parentheses.

Trying to access the list at an index that is out of range raises an IndexError, so the except block runs.

You don't have to store the error in a variable in the except block if you don't need it.

main.py
my_list = [] try: raise ValueError('something went wrong') except (IndexError, ZeroDivisionError): # 👇️ this runs pass

If an error of a different type is raised in the try block, the except block doesn't run. Instead, the error crashes the program.

main.py
my_list = [] try: raise ValueError('something went wrong') except (IndexError, ZeroDivisionError) as e: pass # ⛔️ ValueError: something went wrong

The try block raises a ValueError which is not present in the parenthesized tuple, so the except block doesn't run.

You can use this approach to catch as many exceptions in one except block as necessary.

main.py
my_list = [] try: raise ValueError('something went wrong') except (IndexError, ZeroDivisionError, ValueError) as e: # 👇️ this runs pass

An alternative to catching multiple exceptions in one except block is to use a single try block with multiple except blocks.

main.py
my_list = [] try: raise ValueError('something went wrong') except IndexError as e: pass except ZeroDivisionError as e: pass except ValueError as e: # 👇️ this runs pass

The try statement has 3 except statements.

If the code in the try block raises an IndexError, a ZeroDivisionError or a ValueError, the corresponding except block is run.

This approach gives us more control if we need to handle different exception types that may occur in the same try block differently.

You can view all of the exception classes in Python in the Exception hierarchy list in the docs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.