网友问题:
我知道我可以做到:
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
现在这真的行不通了,因为它与以下语法匹配:
try:
# do something that may fail
except Exception, e:
# say please
因此,我捕捉两个不同异常的努力并没有完全实现。
有没有办法做到这一点?
网友回答:
如何在一行中捕获多个异常(块除外)
这样做:
try:
may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
handle(error) # might log or have some other default behavior...
由于使用逗号将错误对象分配给名称的旧语法,因此括号是必需的。关键字用于分配。您可以为错误对象使用任何名称,我个人更喜欢。as
error
要以当前与 Python 向前兼容的方式执行此操作,您需要用逗号分隔异常并用括号将它们括起来,以区别于早期语法,后者通过在要用逗号捕获的异常类型后跟将异常实例分配给变量名称。
下面是一个简单用法的示例:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
sys.exit(0)
我只指定这些异常以避免隐藏错误,如果我遇到错误,我希望从中跟踪完整的堆栈。
此处记录了以下内容:https://docs.python.org/tutorial/errors.html
您可以将异常分配给变量(很常见,但如果异常处理时间较长,或者 IDE 仅突出显示大于该值的选择,则可能更喜欢更详细的变量,就像我所做的那样。实例具有 args 属性。下面是一个示例:e
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError) as err:
print(err)
print(err.args)
sys.exit(0)
Note that in Python 3, the object falls out of scope when the block is concluded.err
except
You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:
import sys
try:
mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
print err
print err.args
sys.exit(0)
If you see the comma name assignment in your codebase, and you’re using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.
suppress
The accepted answer is really 4 lines of code, minimum:
try:
do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
The , , lines can be handled in a single line with the suppress context manager, available in Python 3.4:try
except
pass
from contextlib import suppress
with suppress(IDontLikeYouException, YouAreBeingMeanException):
do_something()
So when you want to on certain exceptions, use .pass
suppress
网友回答:
来自 Python 文档:
except 子句可以将多个异常命名为括号元组,例如
except (IDontLikeYouException, YouAreBeingMeanException) as e:
pass
或者,仅适用于 Python 2:
except (IDontLikeYouException, YouAreBeingMeanException), e:
pass
用逗号将异常与变量分开在 Python 2.6 和 2.7 中仍然有效,但现在已弃用,在 Python 3 中不起作用;现在您应该使用 .as
网友回答:
From Python documentation -> 8.3 Handling Exceptions:
A statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be
executed. Handlers only handle exceptions that occur in the
corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a
parenthesized tuple, for example:try
except (RuntimeError, TypeError, NameError): pass
Note that the parentheses around this tuple are required, because
except was the syntax used for what is normally
written as in modern Python (described
below). The old syntax is still supported for backwards compatibility.
This means is not equivalent to
but to
which is not what you want.ValueError, e:
except ValueError as e:
except RuntimeError, TypeError
except (RuntimeError, TypeError):
except RuntimeError as
TypeError:
模板简介:该模板名称为【我如何Python在一行中捕获多个异常(块除外)】,大小是暂无信息,文档格式为.html,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。