在一行中捕获多个异常(块除外) [英] Catch multiple exceptions in one line (except block)

查看:107
本文介绍了在一行中捕获多个异常(块除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以做:

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

我也可以这样做: p>

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):

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.

有没有办法这样做?

推荐答案

Python文档


一个except子句可以将多个异常称为括号元组,例如

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中不起作用现在你应该使用作为

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

这篇关于在一行中捕获多个异常(块除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆