Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (16.4k points)

I know this works,

try:

    # do something that may fail

except:

    # do this if ANYTHING goes wrong

I know, even this works:

try:

    # do something that may fail

except IDontLikeYouException:

    # say please

except YouAreTooShortException:

    # stand on a laddertry:

    # do something that may fail

except IDontLikeYouException:

    # say please

except YouAreTooShortException:

    # stand on a ladder

But If I try to do the same thing inside two different exceptions, Like this :

try:

    # do something that may fail

except IDontLikeYouException:

    # say please

except YouAreBeingMeanException:

    # say please

I just want to know whether I can do this :

try:

    # do something that may fail

except IDontLikeYouException, YouAreBeingMeanException:

    # say please

Since it matches the syntax, it won't work for:

try:

    # do something that may fail

except Exception, e:

    # say please

Is there any way, so that I can catch two distinct exceptions?

1 Answer

0 votes
by (26.4k points)
edited by

From this python concept, 

An except clause may name multiple exceptions as a parenthesized tuple.

Example :

except (IDontLikeYouException, YouAreBeingMeanException) as e:

    pass

for python 2:

except (IDontLikeYouException, YouAreBeingMeanException), e:

    pass

In python 2.6, If you separate the exception from the variable with a comma will still work, Even in Python 2.7 it works. But in Python 3, it won't work. So, now you should be using 'as'

For more details about Python, Join our Python online course

Related questions

Browse Categories

...