Python 异常处理

参考: https://www.cnblogs.com/klchang/p/4635040.html

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, e:
    print 'str(Exception):	', str(Exception)
    print 'str(e):		', str(e)
    print 'repr(e):	', repr(e)
    print 'e.message:	', e.message
    print 'traceback.print_exc():'; traceback.print_exc()
    print 'traceback.format_exc():
%s' % traceback.format_exc()

示例结果:

二、自定义异常

定义了一个名为 CustomException 的基类,其他两个异常(ValueTooSmallException 和 ValueTooLargeException)都派生自该类,将它们放入 myexceptions.py 模块中:

class CustomException(Exception):
   """Base class for other exceptions"""
   pass

class ValueTooSmallException(CustomException):
   """Raised when the input value is too small"""
   pass

class ValueTooLargeException(CustomException):
   """Raised when the input value is too large"""
   pass

注意: 文件的命名不要过于普通,否则容易与其它文件重名,导致import失败

原文地址:https://www.cnblogs.com/ying-chease/p/9493857.html