从异常对象中获取行号

use*_*619 4 python python-2.7

我已经定义了一个自定义 Exception 对象,并想获取异常的行号。

class FlowException(Exception):
    pass

def something():
    print 2/3
    print 1/2
    print 2/0


try:
   something()
except Exception as e:
   raise FlowException("Process Exception", e)
Run Code Online (Sandbox Code Playgroud)

现在,如果 something() 中有异常,它会抛出 FlowException 但它没有给我确切的行号,我如何从 FlowException 中获取行号(即;它在 2/0 执行时失败)?

这是输出:--

raise FlowException("Process Exception", e)
__main__.FlowException: ('Process Exception', ZeroDivisionError('integer division or modulo by zero',))
[Finished in 0.4s with exit code 1]
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 5

traceback对象在tb_lineno属性中保存该信息:

import sys

# ...
except Exception as e:
   trace_back = sys.exc_info()[2]
   line = trace_back.tb_lineno
   raise FlowException("Process Exception in line {}".format(line), e)
Run Code Online (Sandbox Code Playgroud)