說(shuō)明
1、程序可以通過(guò)創(chuàng)建一個(gè)新的異常類來(lái)命名它們自己的異常。異常應(yīng)該是典型的繼承自Exception類,直接或間接的方式。
2、異常python有一個(gè)大基類,繼承了Exception。因此,我們的定制類也必須繼承Exception。
實(shí)例
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 ( '請(qǐng)輸入 --> ' ) if len (s) < 3 : # raise引發(fā)一個(gè)你定義的異常 raise ShortInputException( len (s), 3 ) except ShortInputException as result: #x這個(gè)變量被綁定到了錯(cuò)誤的實(shí)例 print ( 'ShortInputException: 輸入的長(zhǎng)度是 %d,長(zhǎng)度至少應(yīng)是 %d' % (result.length, result.atleast)) else : print ( '沒(méi)有異常發(fā)生' ) main() |
知識(shí)點(diǎn)擴(kuò)展:
自定義異常類型
1
2
3
4
5
6
7
|
#1.用戶自定義異常類型,只要該類繼承了Exception類即可,至于類的主題內(nèi)容用戶自定義,可參考官方異常類 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 ( "姓名長(zhǎng)度是" + str ( self .leng) + ",超過(guò)長(zhǎng)度了" ) |
捕捉用戶手動(dòng)拋出的異常
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.捕捉用戶手動(dòng)拋出的異常,跟捕捉系統(tǒng)異常方式一樣 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) #調(diào)用函數(shù),執(zhí)行 name_Test() = = = = = = = = = = 執(zhí)行結(jié)果如下: = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = enter your naem:aaafsdf 捕捉到異常了 Traceback (most recent call last): 打印異常信息: 姓名長(zhǎng)度是 7 ,超過(guò)長(zhǎng)度了 姓名長(zhǎng)度是 7 ,超過(guò)長(zhǎng)度了 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用戶自定義異常的實(shí)例講解的詳細(xì)內(nèi)容,更多關(guān)于python用戶如何自定義異常的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://www.py.cn/jishu/jichu/31895.html