我知道我能做到:
try:
# do something that may fail
except:
# do this if ANYTHING goes wrong
我也可以这样做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreTooShortException:
# stand on a ladder
但是如果我想在两个不同的异常中做同样的事情,我现在能想到的最好的就是这样做:
try:
# do something that may fail
except IDontLikeYouException:
# say please
except YouAreBeingMeanException:
# say please
有什么方法可以让我做这样的事情(因为在这两种异常(exception)情况下采取的行动都是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 Documentation :
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
或者,仅适用于 Python 2:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
在 Python 2.6 和 2.7 中用逗号将异常与变量分开仍然可以使用,但现在已弃用并且在 Python 3 中不起作用;现在你应该使用 as
。
https://stackoverflow.com/questions/6470428/