Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从异常对象获取行号_Python_Python 2.7 - Fatal编程技术网

Python 从异常对象获取行号

Python 从异常对象获取行号,python,python-2.7,Python,Python 2.7,我已经定义了一个自定义异常对象,并希望获得异常的行号 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) 现在,如果something()中存在异常,它会抛出Flo

我已经定义了一个自定义异常对象,并希望获得异常的行号

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)
现在,如果something()中存在异常,它会抛出FlowException,但没有给出确切的行号,那么如何从FlowException中获取行号(即,当它执行2/0时失败)

以下是输出:--

在Python3.6上测试

class FlowException(Exception):
    pass

def something():
    raise ValueError

try:
   something()
except Exception as e:
    raise FlowException("Process Exception", e)
输出具有行号:

Traceback (most recent call last):
  File "/Users/diman/PycharmProjects/invites/test.py", line 8, in <module>
    something()
  File "/Users/diman/PycharmProjects/invites/test.py", line 5, in something
    raise ValueError
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/diman/PycharmProjects/invites/test.py", line 10, in <module>
    raise FlowException("Process Exception", e)
__main__.FlowException: ('Process Exception', ValueError())
对象在
tb\u 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)
您可以使用模块


查看如何使用它。

在Python3上打印
FlowException
时,您会得到一个错误,如“在处理[original exception stack]时遇到FlowException[flow exception stack]”可能是
import logging
logger = logging.getLogger()

try:
    something()
except Exception as e:
    logger.exception(e)
    raise FlowException("Process Exception", e)
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)