问题

我知道我可以做:

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

我也可以这样做:

try:
    # do something that may fail
except IDontLikeYourFaceException:
    # put on makeup or smile
except YouAreTooShortException:
    # stand on a ladder

但是如果我想在两个不同的例外中做同样的事情,我现在最好的想法是这样做:

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

有任何方法,我可以做这样的事情(因为采取的行动,在两个例外是<代码说请请):

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

现在这不会工作,因为它匹配的语法:

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

所以,我努力捕捉两个不同的例外并不完全通过.

有办法吗?



解决方法

Python文档:

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

except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

使用逗号将异常与变量分隔仍然可以在Python 2.6和2.7中使用,但是现在已经废弃,在Python 3中不起作用;现在你应该使用作为.




相关问题推荐