#異常處理
try:
xxxx 可能發生錯誤邏輯語句
except:
xxx 報錯后處理
else:
xxx 沒發生錯誤語句
finally
xxx 不管有沒有錯都執行
-- 名稱異常(NameError):變量未定義。
-- 類型異常(TypeError):不同類型數據進行運算。
-- 索引異常(IndexError):超出索引范圍。
-- 屬性異常(AttributeError):對象沒有對應名稱的屬性。
-- 鍵異常(KeyError):沒有對應名稱的鍵。
-- 為實現異常(NotImplementedError):尚未實現的方法。
-- 異常基類Exception。
raise 語句:人工拋出異常
自定義異常類
class WeightError(Exception):
def __init__(self, message="", code="", id=0):
# super().__init__()
self.message = message
self.code = code
self.id = id
class Wife:
def __init__(self, name="", weight=0):
self.name = name
self.weight = weight
@property
def weight(self):
return self.__weight
@weight.setter
def weight(self, value):
if 20 <= value <= 200:
self.__weight = value
else:
# 有意拋出異常
# 傳遞的錯誤信息:錯誤原因,錯誤代碼,錯誤編號,.....
# raise Exception("體重超過范圍")
raise WeightError("體重超過范圍", "if 20 <= value <= 200", 1001)