知識點回顧:
1.異常處理機制
2.debug過程中的各類報錯
3.try-except機制
4.try-except-else-finally機制
在即將進入深度學習專題學習前,我們最后差缺補漏,把一些常見且重要的知識點給他們補上,加深對代碼和流程的理解。
作業:理解今日的內容即可,可以檢查自己過去借助ai寫的代碼是否帶有try-except機制,以后可以嘗試采用這類寫法增加代碼健壯性。
一、異常處理機制
try:result = 10 / 0
except ZeroDivisionError as e:print(f"發生除零錯誤: {e}")
except Exception as e:print(f"未知錯誤: {e}")
else:print("計算成功")
finally:print("清理資源")
二、debug過程中的各類報錯
try:import non_existent_module # ModuleNotFoundError
except ImportError as e:print(f"導入錯誤: {e}")def bad_logic(x):return x + "2" try:bad_logic(10)
except TypeError as e:print(f"類型錯誤: {e}")
三、try-except機制
def read_file(filename):try:with open(filename, 'r') as f:content = f.read()return contentexcept FileNotFoundError:print(f"文件 {filename} 不存在")except PermissionError:print("沒有讀取權限")except UnicodeDecodeError:print("文件編碼錯誤")read_file("non_existent.txt")
read_file("/root/.bashrc")
read_file("binary_file.bin")
四、try-except-else-finally機制
def process_transaction(amount):balance = 1000try:if amount < 0:raise ValueError("金額不能為負數") new_balance = balance - amountexcept ValueError as e:print(f"交易失敗: {e}")except TypeError:print("錯誤:金額類型無效")else:print(f"交易成功,新余額: {new_balance}")return new_balancefinally:print("記錄交易日志到數據庫")process_transaction(500)
process_transaction(-100)
process_transaction("abc")
關鍵點總結
-
異常類型匹配:
except
?塊按順序匹配異常類型 -
異常層級:
Exception
?是所有內置異常的基類 -
主動拋出異常:使用?
raise
?手動觸發異常 -
資源清理:
finally
?塊適合做資源釋放操作 -
錯誤隔離:將可能出錯的代碼盡量縮小在?
try
?塊中