2

Python捕获异常时打印出错误所在行数

 7 months ago
source link: https://chegva.com/5917.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python捕获异常时打印出错误所在行数

在开发中,可能一个源文件代码行数比较多,尤其变量在多个地方存在,报错定位不好确定时,可以使用以下代码来捕获异常并打印出错误所在行数。这样就可以便于快速定位到出问题的地方啦。

import sys

try:
    ...
except Exception as e:
    print(f"Error on line {sys.exc_info()[-1].tb_lineno}: {str(e)}")

# 直接 print(e) 的效果:
'NoneType' object has no attribute 'number_plate'

# 打印出错误行数的效果:
Error on line 78: 'NoneType' object has no attribute 'number_plate'
Python

打印异常的堆栈信息:

import traceback

try:
    open("nonexistent_file.txt")
except Exception:
    print(traceback.format_exc())
Python

会打印出完整的堆栈跟踪信息,包括错误发生的位置和调用堆栈。

安志合个人博客,版权所有 丨 如未注明,均为原创 丨 转载请注明转自:https://chegva.com/5917.html | ☆★★每天进步一点点,加油!★★☆ | 

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK