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 catch multiple exceptions in one line (except block) in Python?

I can raise multiple exceptions like this

try:
     #do something
except someException:
      #handle_exception()

And like this

try:
      #do something else
except someotherException:
       #handle_exception()

 How do I catch multiple exceptions in one except block?


1 Answer
Manogna

We catch multiple exceptions in one except block as follows

An except clause may name multiple exceptions as a parenthesized tuple, for example

try:
raise_certain_errors():
except (CertainError1, CertainError2,…) as e:
handle_error()

Separating the exception from the variable with a comma still works in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now we should use ‘as’.

The parentheses are necessary as the commas are used to assign the error objects to names. The ‘as’ keyword is for the assignment. We can use any name for the error object like ‘error’, ‘e’, or ‘err’

Given code can be written as follows

try:
#do something
except (someException, someotherException) as err:
#handle_exception()
Advertisements

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