We can use a try-except block to catch exceptions and process them. Sometimes we call a function that may throw multiple types of exceptions depending on the arguments, processing logic etc. In this tutorial, we will learn how to catch multiple exceptions in python.
Python Catch Multiple Exceptions
Let’s say we have a function defined as follows:
import math def square(x): if int(x) is 0: raise ValueError('Input argument cannot be zero') if int(x) < 0: raise TypeError('Input argument must be positive integer') return math.pow(int(x), 2)
We can catch both
TypeError in different except block.
while True: try: y = square(input('Please enter a number\n')) print(y) except ValueError as ve: print(type(ve), '::', ve) except TypeError as te: print(type(te), '::', te)
I have put the try-except block in while True loop so that I can run the scenario of catching multiple exceptions.
Please enter a number 10 100.0 Please enter a number -5 <class 'TypeError'> :: Input argument must be positive integer Please enter a number 0 <class 'ValueError'> :: Input argument cannot be zero Please enter a number ^D Traceback (most recent call last): File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_catch_multiple_exceptions.py", line 15, in y = square(input('Please enter a number\n')) EOFError: EOF when reading a line Process finished with exit code 1
Catch Multiple Exceptions in a single except block
If you notice the except block code, it’s same for both the exception types. If that is the case, we can remove the code redundancy by passing the tuple of exception types in the except block.
Here is the rewrite of above code where we are catching multiple exceptions in a single except block.
while True: try: y = square(input('Please enter a number\n')) print(y) except (ValueError, TypeError) as e: print(type(e), '::', e)
The output will be exactly the same as earlier. We can use this approach when the code in except block is the same for multiple exceptions being caught.