我已经定义了一个自定义的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)
现在,如果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]
答案 0 :(得分:0)
在Python 3.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())
对于Python 2,尝试使用内部记录器&#34; .exception()&#34;方法而不是使用monstrous&#34; sys&#34;模块。
import logging
logger = logging.getLogger()
try:
something()
except Exception as e:
logger.exception(e)
raise FlowException("Process Exception", e)
答案 1 :(得分:0)
traceback
对象保存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)
属性中的信息:
functions.php
答案 2 :(得分:0)
您可以使用 traceback 模块。
请参阅Log exception in python如何使用它。