python用戶自定義異常的實例講解
1、程序可以通過創(chuàng)建一個新的異常類來命名它們自己的異常。異常應該是典型的繼承自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引發(fā)一個你定義的異常 raise ShortInputException(len(s), 3) except ShortInputException as result:#x這個變量被綁定到了錯誤的實例print(’ShortInputException: 輸入的長度是 %d,長度至少應是 %d’% (result.length, result.atleast)) else:print(’沒有異常發(fā)生’)main()
知識點擴展:
自定義異常類型
#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('姓名長度是'+str(self.leng)+',超過長度了')
捕捉用戶手動拋出的異常
#1.捕捉用戶手動拋出的異常,跟捕捉系統(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):打印異常信息: 姓名長度是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用戶自定義異常的實例講解的詳細內(nèi)容,更多關(guān)于python用戶如何自定義異常的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 用xslt+css讓RSS顯示的跟網(wǎng)頁一樣漂亮2. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字3. 《CSS3實戰(zhàn)》筆記--漸變設計(一)4. 測試模式 - XSL教程 - 55. Ajax實現(xiàn)異步加載數(shù)據(jù)6. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)7. ASP.NET Core自定義中間件的方式詳解8. html5手機觸屏touch事件介紹9. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效10. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例
