python - 处理出现在 except 子句中的 Python 异常

标签 python exception

我在 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 (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 中实现)——这是一本有趣的读物。我今天学到了一些新东西。

关于python - 处理出现在 except 子句中的 Python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2106475/

相关文章:

python - 在python中将图像转换为字节文字

python - 如何将 Eigen::Ref 与 pybind11 一起使用?

perl - 从 PERL 的 $sftp->get or do {...} 中获取错误文本

java - Gradle依赖问题,java.lang.NoClassDefFoundError,但是编译通过

java - 何时为构造函数抛出异常

c++ - 记录 boost::exception 同时避免文件/行/函数和唠叨

python - 在 python 中获取名称错误

python - 如何在谷歌应用引擎中执行多个异步查询?

javascript - 是否有可能在 Electron 主进程中捕获渲染进程的异常?

python - 用使用静态全局变量的 SWIG 包装 C 代码