9

python 中的一个常见模式是捕获上游模块中的错误并将该错误重新引发为更有用的东西。

try:
    config_file = open('config.ini', 'r')
except IOError:
    raise ConfigError('Give me my config, user!')

这将生成表单的堆栈跟踪

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
__main__.ConfigError: Give me my config, user!

有没有办法访问包装的异常以生成更像这样的堆栈跟踪?

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
__builtin__.IOError: File Does not exist.
Exception wrapped by:
  File "<stdin>", line 4, in <module>
__main__.ConfigError: Give me my config, user!

编辑:

我试图解决的问题是一些第 3 方代码最多可以包装异常 3 次,我希望能够确定根本原因,即检查异常堆栈并确定异常根本原因的通用方法无需向 3rd 方模块添加任何额外代码。

4

2 回答 2

10

This is known as Exception Chaining and is suported in Python 3.

PEP 3134: http://www.python.org/dev/peps/pep-3134/

In Python 2, the old exception is lost when you raise a new one, unless you save it in the except block.

于 2012-01-25T09:14:43.950 回答
4

使用traceback 模块。它将允许您访问最近的回溯并将其存储在字符串中。例如,

import traceback
try:
    config_file = open('config.ini', 'r')
except OSError:
    tb = traceback.format_exc()
    raise ConfigError('Give me my config, user!',tb)

The "nested" traceback will be stored in tb and passed to ConfigError, where you can work with it however you want.

于 2012-01-25T03:34:19.223 回答