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