debugpythonCriticalCanonical
How can I catch multiple exceptions in one line? (in the "except" block)
Viewed 0 times
howlinetheexceptblockexceptionsmultiplecancatchone
Problem
I know that I can do:
I can also do this:
But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:
Is there a way that I can do something like this (since the action to take in both exceptions is to
Now this really won't work, as it matches the syntax for:
So, my effort to catch the two distinct exceptions doesn't exactly come through.
Is there a way to do this?
try:
# do something that may fail
except:
# do this if ANYTHING goes wrongI can also do this:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladderBut if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say pleaseIs there a way that I can do something like this (since the action to take in both exceptions is to
say please):try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say pleaseNow this really won't work, as it matches the syntax for:
try:
# do something that may fail
except Exception, e:
# say pleaseSo, my effort to catch the two distinct exceptions doesn't exactly come through.
Is there a way to do this?
Solution
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
Or, for Python 2 only:
Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
passOr, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
passSeparating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using
as.Code Snippets
except (IDontLikeYouException, YouAreBeingMeanException) as e:
passexcept (IDontLikeYouException, YouAreBeingMeanException), e:
passContext
Stack Overflow Q#6470428, score: 5280
Revisions (0)
No revisions yet.