Python用戶自定義異常的實現
實際開發中,有時候系統提供的異常類型不能滿足開發的需求。這時候你可以通過創建一個新的異常類來擁有自己的異常。異常類繼承自 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
系統的自帶的異常只要觸發會自動拋出,比如NameError,但用戶自定義的異常需要用戶自己決定什么時候拋出。raise 唯一的一個參數指定了要被拋出的異常。它必須是一個異常的實例或者是異常的類(也就是 Exception 的子類)。大多數的異常的名字都以'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) #調用函數,執行name_Test()-----------------執行時滿足條件后拋出一個用戶定義的異常如下:--------------------------------------enter your naem:是打發斯蒂芬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.捕捉用戶手動拋出的異常,跟捕捉系統異常方式一樣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 自定義異常內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: