How to use the ‘except’ clause with multiple exceptions in Python?

It is possible to define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under except clause.

In general, the syntax for multiple exceptions is as follows

Except(Exception1, Exception2,…ExceptionN) as e:

When we define except clause in this way, we expect the same code to throw different exceptions. Also, we want to take the action in each case.

Example code

import sys
d = 8
d = d + '5'
except(TypeError, SyntaxError)as e:
print sys.exc_info()

We get output as shown

(<type 'exceptions.TypeError'>, TypeError("unsupported operand type(s) for
 +: 'int' and 'str'",), <traceback object at 0x0000000002954748>)

Updated on: 27-Sep-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started