【问题标题】:When I catch an exception, how do I get the type, file, and line number of the previous frame?捕获异常时,如何获取上一帧的类型、文件和行号?
【发布时间】:2010-11-20 10:59:02
【问题描述】:

来自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

【问题讨论】:

    标签: python exception exception-handling error-handling


    【解决方案1】:

    tb.tb_next是你的朋友:

    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_next.tb_lineno)
    
    runTest()
    

    traceback module 不仅可以做到这一点,而且还不止于此:

    import traceback
    
    def workerFunc():
        return 4/0
    
    def runTest():
        try:
            print workerFunc()
        except:
            print traceback.format_exc()
    
    runTest()
    

    【讨论】:

      【解决方案2】:

      你需要找到回溯的底部,所以你需要循环直到没有更多的帧。执行此操作以找到您想要的框架:

      while tb.tb_next:
          tb = tb.tb_next
      

      在 sys.exc_info 之后。无论发生多少调用帧,这都会找到异常。

      【讨论】:

        【解决方案3】:

        添加一行:

            tb = tb.tb_next
        

        就在您致电 sys.exc_info 之后。

        请参阅“Traceback objects”下的文档here

        【讨论】:

          猜你喜欢
          • 2010-11-19
          • 1970-01-01
          • 1970-01-01
          • 2011-01-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-26
          相关资源
          最近更新 更多