Python用戶自定義異常的實現(xiàn)
實際開發(fā)中,有時候系統(tǒng)提供的異常類型不能滿足開發(fā)的需求。這時候你可以通過創(chuàng)建一個新的異常類來擁有自己的異常。異常類繼承自 Exception 類,可以直接繼承,或者間接繼承。
常見的內置異常有:
#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
系統(tǒng)的自帶的異常只要觸發(fā)會自動拋出,比如NameError,但用戶自定義的異常需要用戶自己決定什么時候拋出。raise 唯一的一個參數(shù)指定了要被拋出的異常。它必須是一個異常的實例或者是異常的類(也就是 Exception 的子類)。大多數(shù)的異常的名字都以'Error'結尾,所以實際命名時盡量跟標準的異常命名一樣。
#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) #調用函數(shù),執(zhí)行name_Test()-----------------執(zhí)行時滿足條件后拋出一個用戶定義的異常如下:--------------------------------------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.捕捉用戶手動拋出的異常
#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) #調用函數(shù),執(zhí)行name_Test()==========執(zhí)行結果如下:==================================================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用戶自定義異常的實現(xiàn)的文章就介紹到這了,更多相關Python 自定義異常內容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. Hybris在idea中debug配置方法詳解2. 在idea中為注釋標記作者日期操作3. jsp cookie+session實現(xiàn)簡易自動登錄4. XPath入門 - XSL教程 - 35. 通過CSS數(shù)學函數(shù)實現(xiàn)動畫特效6. .NET Core Web APi類庫內嵌運行的方法7. .NET6使用ImageSharp實現(xiàn)給圖片添加水印8. ASP.NET MVC實現(xiàn)橫向展示購物車9. ASP.NET MVC使用Boostrap實現(xiàn)產品展示、查詢、排序、分頁10. .net如何優(yōu)雅的使用EFCore實例詳解
