1. 程式人生 > 程式設計 >Python使用者自定義異常的實現

Python使用者自定義異常的實現

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

常見的內建異常有:

Python使用者自定義異常的實現

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)

到此這篇關於Python使用者自定義異常的實現的文章就介紹到這了,更多相關Python 自定義異常內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!