#将多行的异常变成一行
原问题地址:http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block
##问题:
我知道我可以这样做:
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
有没有什么办法让我可以实现下面的功能(因为在这两种异常中都要做say please):
try:
# do something that may fail
except IDontLIkeYouException, YouAreBeingMeanException:
# say please
现在这样做行不通,因为它和下面代码的语法相匹配:
try:
# do something that may fail
except Exception, e:
# say please
所以,我为了捕捉到这两种不同的异常所做的努力并没有奏效。
有办法成功做到吗?
##回答:
用圆括号括起来
except (IDontLIkeYouException, YouAreBeingMeanException) as e:
pass
在Python 2.6和Python2.7中仍然可以用逗号把异常分开,但现在这样做已经过时了,不再适用于现在所使用的Python 3。现在你应该使用as。