Python中获取异常(Exception)信息
来源:互联网 发布:淘宝旺旺位置设置 编辑:程序博客网 时间:2024/05/17 06:44
异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种python中获取异常信息的方法,这里获取异常(Exception)信息采用try...except...程序结构。如下所示
try: ...except Exception as e: ...
1、str(e)
返回字符串类型,只给出异常信息,不包括异常信息的类型,如1/0的异常信息
'integer division or modulo by zero'
2、repr(e)
给出较全的异常信息,包括异常信息的类型,如1/0的异常信息
"ZeroDivisionError('integer division or modulo by zero',)"
3、e.message
获得的信息同str(e)
4、采用traceback模块
需要导入traceback模块,此时获取的信息最全,与python命令行运行程序出现错误信息一致。使用traceback.print_exc()打印异常信息到标准错误,就像没有获取一样,或者使用traceback.format_exc()将同样的输出获取为字符串。你可以向这些函数传递各种各样的参数来限制输出,或者重新打印到像文件类型的对象。
示例如下:
import tracebackprint '########################################################'print "1/0 Exception Info"print '---------------------------------------------------------'try: 1/0except Exception as e: print 'str(Exception):\t', str(Exception) print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print 'e.message:\t', e.message print 'traceback.print_exc():'; traceback.print_exc() print 'traceback.format_exc():\n%s' % traceback.format_exc()print '########################################################'print '\n########################################################' print "i = int('a') Exception Info"print '---------------------------------------------------------'try: i = int('a')except Exception as e: print 'str(Exception):\t', str(Exception) print 'str(e):\t\t', str(e) print 'repr(e):\t', repr(e) print 'e.message:\t', e.message print 'traceback.print_exc():'; traceback.print_exc() print 'traceback.format_exc():\n%s' % traceback.format_exc()print '########################################################'
阅读全文
0 0
- Python中获取异常(Exception)信息
- Python中获取异常(Exception)信息
- Python 异常(Exception)
- Python 异常(Exception)
- jsp exception对象获取异常信息
- JSP获取异常信息的exception对象
- Python中的异常(Exception)
- Python中Exception的异常处理
- Python中捕获异常信息
- Struts2中将global-exception定位到一个Action中处理,及获取其异常信息的方法
- 获取python未知异常信息的方法
- python的异常Exception
- python Exception 异常处理
- Python,异常 exception
- python异常 Exception
- Python Exception 异常处理
- python中获取对象信息
- 根据exception 异常堆栈信息
- 2017.8.9测试 题一 17倍
- The specified JRE installation does not exist
- STL string
- 设计模式-行为-迭代器
- C++双冒号::
- Python中获取异常(Exception)信息
- bzoj 4318: OSU!(概率DP)
- Java程序员从笨鸟到菜鸟之(四)练习
- 回调函数的简单应用
- 设计模式-行为-中介者
- Java七种排序算法教程
- Python 访问私有变量和私有方法
- 【图像处理】MATLAB:频域处理
- codeforces 869A The Artful Expedient