我在 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中实现这个吗?