我在 Python except
子句中有一些代码用于进行一些日志记录,但日志记录代码本身可能会导致异常。就我而言,我想忽略可能发生的任何第二个异常,并引发原始异常。这是一个非常简化的示例:
try:
a = this_variable_doesnt_exist
except:
try:
1/0
except:
pass
raise
运行上面的代码,希望得到:
NameError: name 'this_variable_doesnt_exist' is not defined
但是,在 Python 2.x 中,我得到:
ZeroDivisionError: integer division or modulo by zero
我发现在 Python 3.x 中,它可以满足我的需求。
我在 Python 2.x 文档中找不到太多关于此的评论(除非我错过了)。我可以在 2.x 中实现这一点吗?
最佳答案
我相信您看到的是 exception chaining 的结果, 这是一个 change in Python 3 .
来自 PEP 的动机部分:
During the handling of one exception (exception
A
), it is possible that another exception (exceptionB
) may occur. In today's Python (version 2.4), if this happens, exceptionB
is propagated outward and exceptionA
is lost. In order to debug the problem, it is useful to know about both exceptions. The__context__
attribute retains this information automatically.
然后,PEP 继续详细描述新的异常链(在 Py3k 中实现)——这是一本有趣的读物。我今天学到了一些新东西。
关于python - 处理出现在 except 子句中的 Python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2106475/