Python Program to Catch Multiple Exceptions in One Line – 2024

Hey guys, in this blog we will see a Python Program to Catch Multiple Exceptions in One Line.

Multiple exceptions as a parenthesized tuple

string = input()

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

Input 1

a
2

Output 1

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

Input 2

a
b

Output 2

invalid literal for int() with base 10: 'b'
  • We have used try/except in this example.
  • It will first try to run the try part and will see if it runs successfully.
  • But if it throws any error, it will go in except part and there we have printed the Exception as e.
  • The exception can be of any type of 2 we have provided; TypeError or ValueError.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 517

Leave a Reply

Your email address will not be published. Required fields are marked *