我在Pythonexcept
子句中有一些代码打算进行一些日志记录,但是日志记录代码本身可能会导致异常。在我的例子中,我只想忽略可能发生的任何第二个异常,并引发原始异常。下面是一个非常简单的示例:
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
我发现在Python3.x中,它可以做我想做的事情。
我在Python2.x文档中找不到关于这个的评论(除非我错过了)。我能在2.x内完成吗?
抽象地说:
在Python2.5中做您想要的事情
另一种方法是将异常存储在变量中,然后显式重新引发它:
请注意,您可能不应该只是使用一个简单的
except
来捕获可能出现的所有内容—通常最好是捕获在发生严重且致命的异常(如内存不足)时预期发生的特定异常。我相信你看到的是exception chaining的结果,也就是change in Python 3。
从政治公众人物的动机部分:
PEP接着详细描述了新的异常链(在Py3k中实现),这是一篇有趣的文章。我今天学到了新的东西。
在我的CausedException class中,我为Python 2.x(以及Python 3)处理这个问题,以防您希望传递原因树而不是简单的原因链)。也许它能帮助你。
相关问题 更多 >
编程相关推荐