Python捕获异常堆栈信息的几种方法(小结)

作者:xiemanR 时间:2022-02-19 08:01:30 

程序出错的时候,我们往往需要根据异常信息来找到具体出错的代码。简单地用print打印异常信息并不能很好地追溯出错的代码:


# -*- coding: utf-8 -*-

def foo(a, b):
 c = a + b
 raise ValueError('test')
 return c

def bar(a):
 print('a + 100:', foo(a, 100))

def main():
 try:
   bar(100)
 except Exception as e:
   print(repr(e))

if __name__ == '__main__':
 main()

输出:

ValueError('test',)

打印的异常信息不够详细,对错误追踪没有多大帮助。这时候异常堆栈信息就派上用场了。下面简单介绍几种打印异常堆栈信息的方法。

1.最简单的方法之一就是使用logging.exception


# -*- coding: utf-8 -*-
import logging

def foo(a, b):
 c = a + b
 raise ValueError('test')
 return c

def bar(a):
 print('a + 100:', foo(a, 100))

def main():
 try:
   bar(100)
 except Exception as e:
   logging.exception(e)

if __name__ == '__main__':
 main()

输出:

ERROR:root:test
Traceback (most recent call last):
  File "E:/git_work/scrapy_ppt/test.py", line 16, in main
    bar(100)
  File "E:/git_work/scrapy_ppt/test.py", line 11, in bar
    print('a + 100:', foo(a, 100))
  File "E:/git_work/scrapy_ppt/test.py", line 6, in foo
    raise ValueError('test')
ValueError: test

从异常堆栈信息中我们可以不费力气就找出错误代码是哪一行。

2.其它方法:


# -*- coding: utf-8 -*-
import traceback
import sys

def foo(a, b):
 c = a + b
 raise ValueError('test')
 return c

def bar(a):
 print('a + 100:', foo(a, 100))

def main():
 try:
   bar(100)
 except Exception as e:
   # 方法二
   traceback.print_exc()

# 方法三
   msg = traceback.format_exc()
   print(msg)

et, ev, tb = sys.exc_info()
   # 方法四
   traceback.print_tb(tb)

# 方法五
   traceback.print_exception(et, ev, tb)

# 方法六
   msg = traceback.format_exception(et, ev, tb)
   for m in msg:
     print(m)

if __name__ == '__main__':
 main()

来源:https://blog.csdn.net/xiemanR/article/details/82934936

标签:Python,异常,堆栈信息
0
投稿

猜你喜欢

  • pytorch 实现冻结部分参数训练另一部分

    2023-06-14 16:43:10
  • jQuery实现同一点击,两个不同链接,指向两个不同的iframe

    2010-06-21 10:52:00
  • Uchome1.2 1.5 代码学习 common.php

    2023-11-15 02:56:10
  • [译]“我心中的ebay”

    2008-06-04 12:09:00
  • matplotlib基本图形绘制操作实例

    2023-07-14 18:18:01
  • 如何在2003系统注册fso组件

    2010-11-29 19:55:00
  • python神经网络学习利用PyTorch进行回归运算

    2023-02-24 13:30:47
  • python抓取京东商城手机列表url实例代码

    2022-11-11 18:23:04
  • JavaScript 数组的 uniq 方法

    2007-12-07 18:28:00
  • Oracle数据库系统使用经验六则

    2010-07-26 13:22:00
  • Python timeit模块的使用实践

    2023-09-15 00:36:55
  • Python 获取div标签中的文字实例

    2023-03-27 01:53:53
  • python 限制函数调用次数的实例讲解

    2023-11-11 00:34:23
  • 较完善的日历组件js源码(兼容)

    2010-08-08 08:43:00
  • PHP封装的PDO数据库操作类实例

    2023-11-18 04:54:31
  • php上传大文件设置方法

    2023-11-21 19:11:22
  • ASP编程入门进阶(十三):AdRotator & Content Rotator

    2008-09-24 17:47:00
  • Oracle数据库的安全策略

    2010-07-31 13:13:00
  • Yahoo!上的小秘密

    2007-08-23 09:48:00
  • jquery密码强度测试工具源码

    2009-12-23 19:38:00
  • asp之家 网络编程 m.aspxhome.com