Catching Multiple Exceptions in Python
Learn to catch multiple exceptions in Python using try and except.

Pre-requisite knowledge -
Python Exception Handling: Try, Except, Else and Finally
An example based guide to handle Python exceptions using try, except, else and finally keywords.

Let’s say, you are trying to print an element of a list through user input. You are using IndexError
exception in your except block to make sure, the program doesn’t crash if user inputs an index that doesn’t exist.
Code
x = [1, 2, 3, 4]
while True:
user_input = input("Guess a position ==> ")
try:
print(x[int(user_input)])
break
except IndexError as e:
print(f"Guess a number between {-1*len(x)} and {len(x)-1}")
Now, try to run the above code in your Python IDE. As long as user enters an integer, the code will run fine.
Output - 1
Guess a position ==> 5
Guess a number between -4 and 3
Guess a position ==> -1
4
However, what happens if user enters a float?
Output - 2
Guess a position ==> 3.5
Traceback (most recent call last):
File "some_file_location", line 6, in <module>
print(x[int(user_input)])
ValueError: invalid literal for int() with base 10: '3.5'
Now your program has crashed due to a ValueError
exception. You hadn’t taken this exception into account.
There are multiple solutions to this problem.
Solution 1 - Multiple except
blocks for multiple exceptions
Code
x = [1, 2, 3, 4]
while True:
user_input = input("Guess a position ==> ")
try:
print(x[int(user_input)])
break
except IndexError as e:
print(f"Guess a number between {-1*len(x)} and {len(x)-1}")
except ValueError as e:
print("You are only allowed integers")
Output
Guess a position ==> 3.5
You are only allowed integers
Guess a position ==> 10
Guess a number between -4 and 3
Guess a position ==> 1
2
Solution 2 - Catch Multiple Exceptions in a single except block
Code
x = [1, 2, 3, 4]
while True:
user_input = input("Guess a position ==> ")
try:
print(x[int(user_input)])
break
except (IndexError, ValueError) as e:
if e.__class__.__name__ == 'IndexError':
print(f"Guess a number between {-1 * len(x)} and {len(x) - 1}")
elif e.__class__.__name__ == 'ValueError':
print("You are only allowed integers")
else:
print(f"Error occured - {e}")
Output
Guess a position ==> 10
Guess a number between -4 and 3
Guess a position ==> 1.5
You are only allowed integers
Guess a position ==> 2
3
Solution 3 - Use the base Exception
class
Code
x = [1, 2, 3, 4]
while True:
user_input = input("Guess a position ==> ")
try:
print(x[int(user_input)])
break
except Exception as e:
if e.__class__.__name__ == 'IndexError':
print(f"Guess a number between {-1 * len(x)} and {len(x) - 1}")
elif e.__class__.__name__ == 'ValueError':
print("You are only allowed integers")
else:
print(f"Error occured - {e}")
Output
Guess a position ==> 10
Guess a number between -4 and 3
Guess a position ==> 3.5
You are only allowed integers
Guess a position ==> "1"
You are only allowed integers
Guess a position ==> 2
3