如何从自定义FlowException异常对象中获取报错行号?
获取自定义异常中原始错误的行号
好问题!当你直接用raise FlowException(...)抛出自定义异常时,原异常的栈追踪信息会丢失,所以拿不到2/0那一行的行号。这里有两种简单的解决办法:
方法1:保留原异常的上下文(推荐)
Python允许你用raise 自定义异常 from 原异常的语法,把原异常和自定义异常关联起来,这样会自动保留完整的栈追踪信息,包括原始错误的行号。
修改你的代码如下:
class FlowException(Exception): pass def something(): print(2/3) print(1/2) print(2/0) # 这一行会报错 try: something() except Exception as e: # 使用from关键字关联原异常 raise FlowException("Process Exception") from e
运行后你会看到类似这样的输出,里面会明确显示原始错误发生在第7行(也就是print(2/0)那一行):
Traceback (most recent call last): File "test.py", line 9, in <module> something() File "test.py", line 7, in something print(2/0) # 这一行会报错 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "test.py", line 12, in <module> raise FlowException("Process Exception") from e __main__.FlowException: Process Exception
方法2:手动提取原异常的行号
如果你不想保留完整的栈信息,只想把行号加到自定义异常的消息里,可以用traceback模块来解析原异常的__traceback__属性:
import traceback class FlowException(Exception): pass def something(): print(2/3) print(1/2) print(2/0) # 这一行会报错 try: something() except Exception as e: # 提取原始错误的行号 tb = e.__traceback__ frame = tb.tb_frame line_number = frame.f_lineno # 把行号加入异常消息 raise FlowException(f"Process Exception at line {line_number}", e)
运行后输出会直接显示行号:
Traceback (most recent call last): File "test.py", line 14, in <module> raise FlowException(f"Process Exception at line {line_number}", e) __main__.FlowException: ('Process Exception at line 7', ZeroDivisionError('division by zero',))
两种方法里,第一种更符合Python的异常处理规范,能保留完整的错误上下文,方便调试;第二种则更灵活,可以自定义异常消息的格式。
内容的提问来源于stack exchange,提问作者user1050619
相关产品推荐
相关产品推荐

