
说明
1、程序可以通过创建一个新的异常类来命名它们自己的异常。
异常应该是典型的继承自Exception类,直接或间接的方式。
2、异常python有一个大基类,继承了Exception。因此,我们的定制类也必须继承Exception。
实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class ShortInputException(Exception):
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
def main():
try :
s = input( '请输入 --> ' )
if len(s) < 3:
# raise引发一个你定义的异常
raise ShortInputException(len(s), 3)
except ShortInputException as result: #x这个变量被绑定到了错误的实例
print( 'ShortInputException: 输入的长度是 %d,长度至少应是 %d' % (result.length, result.atleast))
else :
print( '没有异常发生' )
main()
|
以上就是python用户自定义异常的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。