python - 当我捕捉到异常时,如何获取上一帧的类型、文件和行号?

标签 python exception exception-handling error-handling

来自 this question ,我现在正在向下一级进行错误处理。也就是说,我调用一个调用另一个更大函数的函数,我想要它在那个更大的函数中失败的地方,而不是在更小的函数中。具体例子。代码是:

import sys, os

def workerFunc():
    return 4/0

def runTest():
    try:
        print workerFunc()
    except:
        ty,val,tb = sys.exc_info()
        print "Error: %s,%s,%s" % (
            ty.__name__,
            os.path.split(tb.tb_frame.f_code.co_filename)[1],
            tb.tb_lineno)

runTest()

输出是:

Error: ZeroDivisionError,tmp2.py,8

但第 8 行是“print workerFunc()”——我知道该行失败了,但我想要之前的行:

Error: ZeroDivisionError,tmp2.py,4

最佳答案

添加一行:

    tb = tb.tb_next

就在您调用 sys.exc_info 之后。

查看文档 here在“追溯对象”下。

关于python - 当我捕捉到异常时,如何获取上一帧的类型、文件和行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1291438/

相关文章:

python - 如何在GAE中设置动态URL?

python - 用于节省内存的 Numpy nditer?

ruby-on-rails - Heroku - ActiveRecord::ConnectionTimeoutError(无法在 5.000 秒内获得数据库连接(等待 5.000 秒))

c# - 正确使用 EnsureSuccessStatusCode 和 IsSuccessStatusCode

c++ - 异常处理(限制异常)

c# - Common.Logging 配置异常

python - Jinja 渲染 matplotlib 图?

python - 转置大数组而不加载到内存中

exception - 在 Azure WorkerRole 中引发异常的性能影响

c# - 通过 WCF 序列化异常