美文网首页
Python中捕获异常错误的各种方法

Python中捕获异常错误的各种方法

作者: Xia_91 | 来源:发表于2018-08-31 20:08 被阅读78次

'''
异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种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 traceback

print '########################################################'
print "1/0 Exception Info"
print '---------------------------------------------------------'
try:
1/0
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 '########################################################'
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 '########################################################'

相关文章

  • Python中捕获异常错误的各种方法

    '''异常信息的获取对于程序的调试非常重要,可以有助于快速定位有错误程序语句的位置。下面介绍几种python中获取...

  • Python异常处理

    Python异常处理 一、捕获异常 1.异常捕获语法 2.错误类型捕获 except:处理所有异常。except ...

  • (三)python错误与异常&面向对象编程

    python错误与异常 语法错误与定位 异常捕获、异常处理 try:xxxexcept: 自定义异常 python...

  • 19.介绍一下except的用法和作用?

    Python的except用来捕获所有异常, 因为Python里面的每次错误都会抛出 一个异常,所以每个程序的错误...

  • Python面向对象2

    异常 捕获异常image.png根据错误类型捕获异常image.png 未知错误捕获image.png 捕获异常完...

  • Python异常处理(个人笔记)

    Python3 异常处理 捕获全部异常 各种异常清单 抛出异常 若想知道是否抛出了异常

  • Python基础教程(第三版)(八)异常

    学习笔记。 8.1 异常是什么 Python使用异常对象表示异常状态,并在遇到错误时引发异常; 异常对象没有被捕获...

  • python异常处理2

    try except捕获异常 try/except语句用来检测try语句块中的错误,从而让except语句捕获异常...

  • Python Debug

    常用方法 try...except 方法捕获异常 Python----面向对象---try....except的详...

  • Python异常处理

    参考 Python菜鸟教程错误与异常 Python 异常处理 错误和异常 Python中(至少)有两种错误:语法错...

网友评论

      本文标题:Python中捕获异常错误的各种方法

      本文链接:https://www.haomeiwen.com/subject/qrpewftx.html