最后活跃于 9 months ago

errno 提供標準錯誤代碼,適用於 檔案操作、系統調用、例外處理,可提高錯誤訊息的可讀性,並方便比對特定錯誤類型。

custom_error_example.py 原始文件
1import errno
2
3def raise_custom_error():
4 raise OSError(errno.EPERM, "無權限執行此操作")
5
6try:
7 raise_custom_error()
8except OSError as e:
9 print(f"捕捉到錯誤: {e.strerror} (錯誤碼: {e.errno})")
10
error_code_checker.py 原始文件
1import errno
2
3ERRORS = {
4 errno.ENOENT: "檔案或目錄不存在",
5 errno.EACCES: "權限不足",
6 errno.EEXIST: "檔案已存在",
7 errno.ENOTDIR: "非目錄",
8}
9
10def check_error(code):
11 return ERRORS.get(code, "未知錯誤")
12
13print(check_error(errno.ENOENT)) # 檔案或目錄不存在
14print(check_error(9999)) # 未知錯誤
15
file_removal_error_handling.py 原始文件
1import errno
2import os
3
4try:
5 os.remove("non_existent_file.txt") # 嘗試刪除不存在的檔案
6except OSError as e:
7 if e.errno == errno.ENOENT:
8 print("錯誤:檔案不存在")
9 elif e.errno == errno.EACCES:
10 print("錯誤:權限不足")
11 else:
12 print(f"其他錯誤: {e}")
13