範例一:烏龜(Turtle) - 風水能量過載例外
文化背景:烏龜代表穩定的風水能量,但能量過高可能「破壞平衡」,就像風水過旺不利環境穩定。
情境:烏龜的能量(energy)有限制,超過 1000 會引發自訂例外,模擬風水能量過載。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class TurtleEnergyOverloadError(Exception): """自訂例外:烏龜能量過載""" pass class Turtle: def __init__(self, energy=100): self.__energy = energy def recharge(self, amount): try: if amount < 0: raise ValueError("能量增量不能為負!") new_energy = self.__energy + amount if new_energy > 1000: raise TurtleEnergyOverloadError("烏龜能量過載,風水失衡!") self.__energy = new_energy return f"烏龜能量充滿:{self.__energy}" except TurtleEnergyOverloadError as e: return f"錯誤:{e}" except ValueError as e: return f"錯誤:{e}" def get_energy(self): return self.__energy turtle = Turtle(energy=900) print(turtle.recharge(50)) # 成功:烏龜能量充滿:950 print(turtle.recharge(100)) # 錯誤:烏龜能量過載,風水失衡! print(turtle.recharge(-10)) # 錯誤:能量增量不能為負! |
執行結果:
例外特性:
- 自訂例外:TurtleEnergyOverloadError 是自訂的例外類,模擬風水能量過載。
- 多重例外處理:捕捉 ValueError(負值輸入)和自訂的 TurtleEnergyOverloadError,展示如何處理不同類型的錯誤。
- 文化連結:烏龜的能量限制反映風水需要平衡的理念,過高能量會引發「失衡」。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class LuckExhaustedError(Exception): """自訂例外:白馬好運耗盡""" pass class Treasure: def bless(self): return "寶物帶來吉祥!" class WhiteHorse(Treasure): def __init__(self, luck_points=100): self.luck_points = luck_points def bless(self): try: if self.luck_points <= 0: raise LuckExhaustedError("白馬好運已耗盡,請稍後再試!") self.luck_points -= 10 return super().bless() + f" 白馬帶來好運!剩餘好運點數:{self.luck_points}" except LuckExhaustedError as e: return f"錯誤:{e}" def ride(self): return "白馬奔馳,風水順暢!" horse = WhiteHorse(luck_points=20) print(horse.bless()) # 成功:寶物帶來吉祥! 白馬帶來好運!剩餘好運點數:10 print(horse.bless()) # 成功:寶物帶來吉祥! 白馬帶來好運!剩餘好運點數:0 print(horse.bless()) # 錯誤:白馬好運已耗盡,請稍後再試! |
執行結果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | class InvalidPrayError(Exception): """自訂例外:無效的祈求者""" pass class MarriageFlower: def bloom(self): return "姻緣花開,庄內好姻緣!" def pray(self, person): try: if not person or not isinstance(person, str): raise InvalidPrayError("祈求者名字無效,需為非空字串!") return f"{person} 向姻緣花祈求,好姻緣即將到來!" except InvalidPrayError as e: return f"錯誤:{e}" flower = MarriageFlower() print(flower.pray("小明")) # 成功:小明 向姻緣花祈求,好姻緣即將到來! print(flower.pray("")) # 錯誤:祈求者名字無效,需為非空字串! print(flower.pray(123)) # 錯誤:祈求者名字無效,需為非空字串! |
例外特性:
- 自訂例外:InvalidPrayError 用於檢查無效輸入,模擬姻緣祈求的條件限制。
- 輸入驗證:檢查 person 是否為非空字串,展示如何在例外處理中進行輸入驗證。
- 文化連結:姻緣花祈求需「真誠」(有效名字),反映文化中對姻緣的尊重。