Join our newsletter for the latest updates.

Python Program to Catch Multiple Exceptions in One Line

In this example, you will learn to catch multiple Python exceptions in one line.

To understand this example, you should have the knowledge of the following Python programming topics:


Multiple exceptions as a parenthesized tuple

string = input()

try:
    num = int(input())
    print(string+num)
except (TypeError, ValueError) as e:
    print(e)

Input

a
2

Output

can only concatenate str (not "int") to str

In the above example, string and an integer cannot be added, so TypeError is caught.

Input

a
b

Output

invalid literal for int() with base 10: 'b'

In the above example, the second input should have been an integer, but we passed a string 'b'.

Note: The error which comes first is caught as an exception in case of multiple exceptions.