python用戶自定義異常的實例講解
1、程序可以通過創建一個新的異常類來命名它們自己的異常。異常應該是典型的繼承自Exception類,直接或間接的方式。
2、異常python有一個大基類,繼承了Exception。因此,我們的定制類也必須繼承Exception。
實例class ShortInputException(Exception): def __init__(self, length, atleast):self.length = lengthself.atleast = atleastdef 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()
知識點擴展:
自定義異常類型
#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)+',超過長度了')
捕捉用戶手動拋出的異常
#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用戶如何自定義異常的資料請關注好吧啦網其它相關文章!
相關文章: