BUG與報錯
一、try else
try:# 可能會引發異常的代碼
except ExceptionType: # 最好指定具體的異常類型,例如 ZeroDivisionError, FileNotFoundError# 當 try 塊中發生 ExceptionType 類型的異常時執行的代碼
except: # 不推薦:捕獲所有類型的異常,可能會隱藏bug# 當 try 塊中發生任何其他未被前面 except 捕獲的異常時執行的代碼
實際應用
try:# 假設 result_operation() 是一個可能出錯的操作value = result_operation()
except SomeError:print("操作失敗,使用默認值。")value = default_value
else:# 只有當 result_operation() 成功時,才執行這里的代碼print(f"操作成功,結果是: {value}。現在進行后續處理...")process_value_further(value)
二、DeBUG
(一)文件目錄不存在?FileNotFoundError
場景:嘗試訪問不存在的文件或目錄。
應對:使用?os.path.exists()
?檢查路徑是否存在,或在?try
?塊中處理異常
import osfile_path = "data/missing_file.txt"try:with open(file_path, "r") as f:data = f.read()
except FileNotFoundError:print(f"錯誤:文件不存在 - {file_path}")# 可選:創建缺失的目錄dir_path = os.path.dirname(file_path)os.makedirs(dir_path, exist_ok=True)
else:print(f"成功讀取文件:{len(data)} 字節")
(二)權限不足 (PermissionError
)
場景:嘗試寫入受保護的目錄或讀取無權限的文件。
應對:檢查文件權限
import ostry:# 嘗試在系統根目錄創建文件(通常會失敗)with open("/system_file.txt", "w") as f:f.write("test")
except PermissionError:print("錯誤:權限不足,無法寫入文件。請檢查文件權限或使用管理員權限運行。")
else:print("文件寫入成功")
(三)目錄非空 (OSError
?或?PermissionError
)
場景:使用?os.rmdir()
?刪除非空目錄。
應對:使用?shutil.rmtree()
?遞歸刪除目錄,或手動清理目錄
import os
import shutildir_path = "data/temp"try:# 嘗試刪除目錄os.rmdir(dir_path) # 僅適用于空目錄
except OSError as e:print(f"錯誤:無法刪除目錄 - {e}")# 可選:遞歸刪除非空目錄try:shutil.rmtree(dir_path)print(f"已遞歸刪除目錄:{dir_path}")except Exception as e2:print(f"仍無法刪除:{e2}")
else:print(f"目錄已成功刪除:{dir_path}")
(四)路徑格式錯誤 (SyntaxError
?或?TypeError
)
場景:路徑包含非法字符(如 Windows 路徑中的?:
)或類型錯誤。
應對:使用?os.path.join()
?構建路徑,或清理用戶輸入
import os# 錯誤示例:手動拼接路徑(可能導致格式錯誤)
invalid_path = "C:/windows:system32" # Windows 路徑中包含非法字符try:with open(invalid_path, "r") as f:pass
except (SyntaxError, TypeError) as e:print(f"錯誤:路徑格式不正確 - {e}")# 正確方式:使用 os.path.join()valid_path = os.path.join("C:", "windows", "system32", "file.txt")print(f"正確路徑示例:{valid_path}")
else:print("操作成功")
(五)文件已存在 (FileExistsError
)
場景:嘗試創建已存在的文件或目錄(未指定?exist_ok=True
)。
應對:檢查文件是否存在,或使用?exist_ok=True
?參數
import osdir_path = "data/existing_dir"try:# 不指定 exist_ok=True(默認 False)os.makedirs(dir_path)
except FileExistsError:print(f"錯誤:目錄已存在 - {dir_path}")# 可選:添加后綴或刪除現有目錄new_dir = f"{dir_path}_{os.getpid()}" # 使用進程ID作為后綴os.makedirs(new_dir)print(f"已創建新目錄:{new_dir}")
else:print(f"目錄創建成功:{dir_path}")
@浙大疏錦行