处理except子句中发生的Python异常

2024-10-06 10:20:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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内完成吗?


Tags: 代码示例记录passthisvariable例子exist
3条回答

抽象地说:

def log_it():
    try:
        1 / 0
    except:
        pass

try:
    this = that
except:
    log_it()
    raise

在Python2.5中做您想要的事情

另一种方法是将异常存储在变量中,然后显式重新引发它:

try:
    this = that
except NameError, e: # or NameError as e for Python 2.6
    try:
        1 / 0
    except:
        pass
    raise e

请注意,您可能不应该只是使用一个简单的except来捕获可能出现的所有内容—通常最好是捕获在发生严重且致命的异常(如内存不足)时预期发生的特定异常。

我相信你看到的是exception chaining的结果,也就是change in Python 3

从政治公众人物的动机部分:

During the handling of one exception (exception A), it is possible that another exception (exception B) may occur. In today's Python (version 2.4), if this happens, exception B is propagated outward and exception A 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中实现),这是一篇有趣的文章。我今天学到了新的东西。

在我的CausedException class中,我为Python 2.x(以及Python 3)处理这个问题,以防您希望传递原因树而不是简单的原因链)。也许它能帮助你。

相关问题 更多 >