Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

If my code has more than one or multiple exceptions, how to write the try-except block to catch multiple exceptions?


1 Answer
Manogna

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
try:
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>)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.