timmy 修订了这个 Gist 9 months ago. 转到此修订
3 files changed, 35 insertions
custom_error_example.py(文件已创建)
| @@ -0,0 +1,9 @@ | |||
| 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})") | |
error_code_checker.py(文件已创建)
| @@ -0,0 +1,14 @@ | |||
| 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)) # 未知錯誤 | |
file_removal_error_handling.py(文件已创建)
| @@ -0,0 +1,12 @@ | |||
| 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}") | |