Python用戶自定義異常的實(shí)現(xiàn)
實(shí)際開發(fā)中,有時(shí)候系統(tǒng)提供的異常類型不能滿足開發(fā)的需求。這時(shí)候你可以通過創(chuàng)建一個(gè)新的異常類來擁有自己的異常。異常類繼承自 Exception 類,可以直接繼承,或者間接繼承。
常見的內(nèi)置異常有:
#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)+',超過長度了')2.如何手動(dòng)拋出異常:raise
系統(tǒng)的自帶的異常只要觸發(fā)會自動(dòng)拋出,比如NameError,但用戶自定義的異常需要用戶自己決定什么時(shí)候拋出。raise 唯一的一個(gè)參數(shù)指定了要被拋出的異常。它必須是一個(gè)異常的實(shí)例或者是異常的類(也就是 Exception 的子類)。大多數(shù)的異常的名字都以'Error'結(jié)尾,所以實(shí)際命名時(shí)盡量跟標(biāo)準(zhǔn)的異常命名一樣。
#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.手動(dòng)拋出用戶自定義類型異常def name_Test(): name = input('enter your naem:') if len(name)>4: raise TooLongExceptin(len(name)) #拋出異常很簡單,使用raise即可,但是沒有處理,即捕捉 else : print(name) #調(diào)用函數(shù),執(zhí)行name_Test()-----------------執(zhí)行時(shí)滿足條件后拋出一個(gè)用戶定義的異常如下:--------------------------------------enter your naem:是打發(fā)斯蒂芬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.捕捉用戶手動(dòng)拋出的異常
#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):打印異常信息: 姓名長度是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)
到此這篇關(guān)于Python用戶自定義異常的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Python 自定義異常內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. JavaScript Reduce使用詳解2. 詳解JAVA 強(qiáng)引用3. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法4. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題5. Python TestSuite生成測試報(bào)告過程解析6. SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解7. 深入了解JAVA 軟引用8. SpringBoot2.0集成MQTT消息推送功能實(shí)現(xiàn)9. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法10. SpringBoot集成Redisson實(shí)現(xiàn)延遲隊(duì)列的場景分析
