Python:用戶自定義異常


實際開發中,有時候系統提供的異常類型不能滿足開發的需求。這時候你可以通過創建一個新的異常類來擁有自己的異常。異常類繼承自 Exception 類,可以直接繼承,或者間接繼承。

1.自定義異常類型 

#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)

 

來自:https://blog.csdn.net/qq_26442553/article/details/81783223


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM