python打印异常信息的两种实现方式
作者:feiyang5260 时间:2023-11-17 15:37:41
1. 直接打印错误
try:
# your code
except KeyboardInterrupt:
print("quit")
except Exception as ex:
print("出现如下异常%s"%ex)
如下例子
try:
2/0
except Exception as e:
print(e)
结果为:division by zero
2. 用traceback模块打印
上述结果看不到具体错误的信息,如行数啥的,不方便调试的时候定位,因此也可以用traceback模块,方便调试
import traceback
try:
2/0
except Exception as e:
traceback.print_exc()
结果为:
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\test1.py", line 3, in <module>
2/0
ZeroDivisionError: division by zero
ps:上述traceback.print_exc()是直接打印错误
还可以用traceback.format_exc()返回字符串,可将错误信息保存在文档日志中
可以说traceback.print_exc()等同于print traceback.format_exc()
来源:https://blog.csdn.net/feiyang5260/article/details/86661103
标签:python,打印,异常信息
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用VB将ASP代码封装成DLL
2007-09-28 12:46:00
Python实现单例模式的四种方式详解
2023-07-12 03:07:43
![](https://img.aspxhome.com/file/2023/5/97345_0s.png)
本机安装PaddlePaddle安装指南及步骤详解
2023-12-18 19:35:57
![](https://img.aspxhome.com/file/2023/3/70773_0s.jpg)
python基础之文件操作
2022-12-23 01:15:53
![](https://img.aspxhome.com/file/2023/9/112149_0s.png)
提高MySQL数据库查询效率的三个实用技巧
2008-12-03 16:40:00
20个常用Python运维库和模块
2023-05-11 21:44:13
编写一个JS组件来说说call和apply的用法
2008-11-23 17:11:00
MySQL基于GTID主从搭建
2024-01-23 18:17:56
Python爬虫破解登陆哔哩哔哩的方法
2021-03-28 14:17:40
Vue Router中应用中间件的方法
2024-05-09 10:42:43
![](https://img.aspxhome.com/file/2023/6/126626_0s.jpg)
python3.5+tesseract+adb实现西瓜视频或头脑王者辅助答题
2022-06-13 04:36:44
![](https://img.aspxhome.com/file/2023/6/93556_0s.jpg)
关于keras中卷积层Conv2D的学习记录
2022-07-16 17:33:16
![](https://img.aspxhome.com/file/2023/0/77890_0s.png)
python+pyqt实现12306图片验证效果
2023-11-02 07:28:18
![](https://img.aspxhome.com/file/2023/7/71387_0s.jpg)
通用分页存储过程
2007-11-28 13:08:00
windows系统中Python多版本与jupyter notebook使用虚拟环境的过程
2022-11-28 13:24:01
![](https://img.aspxhome.com/file/2023/1/112001_0s.png)
Python读取Excel表格,并同时画折线图和柱状图的方法
2023-12-25 07:11:27
![](https://img.aspxhome.com/file/2023/5/117305_0s.jpg)
Python海龟绘图之绘制趣味简笔画
2023-03-13 09:09:40
![](https://img.aspxhome.com/file/2023/6/133426_0s.png)
Python 时间戳之获取整点凌晨时间戳的操作方法
2023-10-10 19:42:33
![](https://img.aspxhome.com/file/2023/4/90444_0s.png)
基于Python实现抢注大词的提词工具
2022-04-07 02:00:20
![](https://img.aspxhome.com/file/2023/8/133448_0s.png)
关于PyQt5主窗口图标显示问题汇总
2022-03-27 08:23:18
![](https://img.aspxhome.com/file/2023/9/85029_0s.png)