在實際開發中,程式幾乎不可能一路順風,輸入錯誤、網路斷線、檔案不存在⋯這些都是程式需要處理的意外事件。
如果我們不處理,程式就會當掉,但如果設計得好,就能優雅地應對。
file = open("data.txt", "r")
content = file.read()
print(content)
如果data.txt不存在,就會報錯:
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
當發生錯誤,程式不會當掉,而是轉到 except 區塊。
程式可以根據不同錯誤類型做不同的處理。
try:
file = open("data.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("檔案不存在")
finally:
print("程式結束,釋放資源。")
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除數不能是 0!")
return a / b
print(divide(10, 2))
print(divide(5, 0)) # 會丟出 ZeroDivisionError
class NegativeNumberError(Exception):
"""自訂例外:不允許負數"""
pass
def square_root(num):
if num < 0:
raise NegativeNumberError("數字不能是負數!")
return num ** 0.5
try:
print(square_root(9)) # OK
print(square_root(-4)) # 會丟出 NegativeNumberError
except NegativeNumberError as e:
print("錯誤:", e)
class ATM:
def init(self, balance=0):
self.__balance = balance
def withdraw(self, amount):
if amount > self.__balance:
raise InsufficientBalanceError("餘額不足!")
self.__balance -= amount
return self.__balance
atm = ATM(500)
try:
print("提領後餘額:", atm.withdraw(200))
print("提領後餘額:", atm.withdraw(400)) # 餘額不足!
except InsufficientBalanceError as e:
print("交易失敗:", e)
這樣的設計比「單純 print 錯誤」更靈活,因為可以讓外部決定怎麼處理錯誤。
學會了錯誤處理(try-except-finally)與自訂例外,程式因此更穩健。
明天,將學習模組與套件(Modules & Packages),進一步整理程式結構,邁向專案化開發!