Python Catch Multiple Exceptions With Examples

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 ValueError and TypeError in different except block.

while True:
        y = square(input('Please enter a numbern'))
    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
Please enter a number
<class 'TypeError'> :: Input argument must be positive integer
Please enter a number
<class 'ValueError'> :: Input argument cannot be zero
Please enter a number
Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/", line 15, in
    y = square(input('Please enter a numbern'))
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:
        y = square(input('Please enter a numbern'))
    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.

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: