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:
1 2 3 4 5 6 7 8 9 |
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 ValueError
and TypeError
in different except block.
1 2 3 4 5 6 7 8 9 10 |
while True: try: y = square(input('Please enter a numbern')) 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.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<span style="color: #008000;"><strong><code> Please enter a number 10 100.0 Please enter a number -5 <class 'TypeError'> :: Input argument must be positive integer Please enter a number <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 numbern')) EOFError: EOF when reading a line Process finished with exit code 1 <img class="alignnone wp-image-28861 size-full" src="http://all-learning.com/wp-content/uploads/2018/09/python-catch-multiple-exceptions1.png" alt="python-catch-multiple-exceptions" width="1200" height="628" /> </code></strong></span> |
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.
1 2 3 4 5 6 7 8 |
while True: try: y = square(input('Please enter a numbern')) 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.