实际开发中,有时候系统提供的异常类型不能满足开发的需求。这时候你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 exception 类,可以直接继承,或者间接继承。
常见的内置异常有:
1.自定义异常类型
1
2
3
4
5
6
7
|
#1.用户自定义异常类型,只要该类继承了exception类即可,至于类的主题内容用户自定义,可参考官方异常类
class toolongexceptin(exception):
"this is user's exception for check the length of name "
def __init__( self ,leng):
self .leng = leng
def __str__( self ):
print ( "姓名长度是" + str ( self .leng) + ",超过长度了" )
|
2.如何手动抛出异常:raise
系统的自带的异常只要触发会自动抛出,比如nameerror,但用户自定义的异常需要用户自己决定什么时候抛出。
raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 exception 的子类)。大多数的异常的名字都以"error"结尾,所以实际命名时尽量跟标准的异常命名一样。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#1.用户自定义异常类型
class toolongexceptin(exception):
"this is user's exception for check the length of name "
def __init__( self ,leng):
self .leng = leng
def __str__( self ):
print ( "姓名长度是" + str ( self .leng) + ",超过长度了" )
#2.手动抛出用户自定义类型异常
def name_test():
name = input ( "enter your naem:" )
if len (name)> 4 :
raise toolongexceptin( len (name)) #抛出异常很简单,使用raise即可,但是没有处理,即捕捉
else :
print (name)
#调用函数,执行
name_test()
- - - - - - - - - - - - - - - - - 执行时满足条件后抛出一个用户定义的异常如下: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
enter your naem:是打发斯蒂芬
traceback (most recent call last):
姓名长度是 6 ,超过长度了
file "d:/pythoyworkspace/file_demo/class_demo/extion_demo.py" , line 21 , in <module>
name_test()
__main__.toolongexceptin: <exception str () failed>
|
3.捕捉用户手动抛出的异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
#1.捕捉用户手动抛出的异常,跟捕捉系统异常方式一样
def name_test():
try :
name = input ( "enter your naem:" )
if len (name)> 4 :
raise toolongexceptin( len (name))
else :
print (name)
except toolongexceptin,e_result: #这里异常类型是用户自定义的
print ( "捕捉到异常了" )
print ( "打印异常信息:" ,e_result)
#调用函数,执行
name_test()
= = = = = = = = = = 执行结果如下: = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
enter your naem:aaafsdf
捕捉到异常了
traceback (most recent call last):
打印异常信息: 姓名长度是 7 ,超过长度了
姓名长度是 7 ,超过长度了
file "d:/pythoyworkspace/file_demo/class_demo/extion_demo.py" , line 16 , in name_test
raise toolongexceptin( len (name))
__main__.toolongexceptin: <exception str () failed>
during handling of the above exception, another exception occurred:
traceback (most recent call last):
file "d:/pythoyworkspace/file_demo/class_demo/extion_demo.py" , line 26 , in <module>
name_test()
file "d:/pythoyworkspace/file_demo/class_demo/extion_demo.py" , line 22 , in name_test
print ( "打印异常信息:" ,e_result)
typeerror: __str__ returned non - string ( type nonetype)
|
到此这篇关于python用户自定义异常的实现的文章就介绍到这了,更多相关python 自定义异常内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/ywxbbbbb/p/9958613.html