所属网站分类: python基础 > 异常处理
作者:浮沉
链接:http://www.pythonheidong.com/blog/article/71/
来源:python黑洞网,专注python资源,python教程,python技术!
我知道你能做到:
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
有什么办法我可以做这样的事情(因为两个异常的结果都是say please):
try:
# do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
# say please
实际上这不起作用,因为python把它当做以下语法:
try:
# do something that may fail
except Exception, e:
# say please
因此,在一行中捕获多个异常并没有实现。
有没有办法做到这一点?
通过阅读官方文档,我找到了答案:
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
或者(仅适用于Python 2):
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
使用逗号将变量与变量分开仍然可以在Python 2.6和2.7中使用,但在Python 3中不起作用; 现在你应该使用as。