在一行中捕獲多個異常(塊除外) - Catch multiple exceptions in one line (except block)

語言: CN / TW / HK

問題:

I know that I can do:我知道我可以做到:

try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

I can also do this:我也可以這樣做:

try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreTooShortException:
    # stand on a ladder

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:但是如果我想在兩個不同的異常中做同樣的事情,我現在能想到的最好的就是這樣做:

try:
    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreBeingMeanException:
    # say please

Is there any way that I can do something like this (since the action to take in both exceptions is to say please ):有什麼辦法可以做這樣的事情(因為在這兩個例外中採取的行動都是say please ):

try:
    # do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
    # say please

Now this really won't work, as it matches the syntax for:現在這真的行不通了,因為它匹配以下語法:

try:
    # do something that may fail
except Exception, e:
    # say please

So, my effort to catch the two distinct exceptions doesn't exactly come through.所以,我努力捕捉這兩個不同的異常並沒有完全實現。

Is there a way to do this?有沒有辦法做到這一點?


解決方案:

參考一: http://stackoom.com/question/R9Fk
參考二: Catch multiple exceptions in one line (except block)
「其他文章」