0

这是我的异常类,

class SampleError(Exception):
    def __init__(self):
        self.history = Stack()

这是功能,

def f(x):
    raise SampleError

运行 f(x) 时,如何存储在引发 SampleError 时创建的堆栈。

一如既往的感谢!

4

4 回答 4

3

如果“存储”是指分配给变量进行分析,请使用sys.exc_info()

import sys
try:
    f()
except:
    exc_type, exc, trace = sys.exc_info() # trace is the traceback object

请注意规范中有关循环引用的警告。

于 2012-04-14T07:49:42.393 回答
1

只需查看回溯模块。它将使您能够从任何实例生成回溯。您还可以在经过一些后期处理后以任何您想要的形式存储。

于 2012-04-14T07:45:14.167 回答
1

也许你正在尝试做这样的事情???

导入回溯

class SampleError(Exception):
    def __init__(self):
        self.history = traceback.extract_stack()

def f(x):
    raise SampleError

try:
    f(5);
except SampleError, e:
    print e.history
    out = traceback.format_list(e.history)
    print out[0]
于 2012-04-14T08:47:38.910 回答
0

如果您只想访问异常属性:

try:
    f()
except SampleError, error:
    history = error.history
于 2012-04-14T09:43:06.830 回答