萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 異常處理完整指南:try/except/finally/else、異常層級、堆疊追蹤與最佳實踐

異常處理是強健程式的基石。本文系統講解 Python 異常機制:try/except/else/finally 完整語法、多重捕獲順序、異常繼承體系、跨層級傳播、自訂異常、with 語句上下文管理,並提供生產級錯誤處理模板。

基礎語法結構

try:
    # 可能拋出異常的代碼
    risky_operation()
except SpecificError as e:
    # 處理特定異常
    handle_error(e)
except AnotherError:
    # 處理另一類異常
    pass
else:
    # 無異常時執行
    success_path()
finally:
    # 無論是否異常都執行(清理資源)
    cleanup()

執行流程圖解

try:
    → 正常 → else → finally → 後續代碼
    → 異常 → 匹配 except → finally → 後續代碼(若未重新拋出)
    → 異常 → 無匹配 except → finally → 向上傳播

實際範例:除零與值轉換錯誤

try:
    print('try...')
    r = 10 / int('a')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')

輸出:

try...
ValueError: invalid literal for int() with base 10: 'a'
finally...
END

異常繼承體系與捕獲順序

所有異常繼承自 BaseException:

BaseException
 ├── KeyboardInterrupt
 ├── SystemExit
 ├── GeneratorExit
 └── Exception
      ├── StandardError (Python 2)
      │    ├── ValueError
      │    ├── ZeroDivisionError
      │    └── ...
      ├── IOError
      ├── ImportError
      └── ...

關鍵規則:except 捕獲該類別及其所有子類。父類別在前會「攔截」子類別:

try:
    foo()
except StandardError as e:  # 捕獲 ValueError、ZeroDivisionError 等所有子類
    print('StandardError')
except ValueError as e:     # 永遠執行不到!
    print('ValueError')

正確順序:子類在前,父類在後。

跨層級傳播:集中處理

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except StandardError as e:
        print('Error!')
    finally:
        print('finally...')

優勢:不需在每層捕獲,在合適層級(如進入點、API 邊界)統一處理。

堆疊追蹤:未捕獲異常的最終輸出

$ python err.py
Traceback (most recent call last):
  File "err.py", line 11, in 
    main()
  File "err.py", line 9, in main
    bar('0')
  File "err.py", line 6, in bar
    return foo(s) * 2
  File "err.py", line 3, in foo
    return 10 / int(s)
ZeroDivisionError: integer division or modulo by zero

自訂異常與最佳實踐

class BusinessError(Exception):
    """業務邏輯異常基類"""
    def __init__(self, code, message):
        self.code = code
        self.message = message
        super(BusinessError, self).__init__(message)

class InsufficientFundsError(BusinessError):
    pass

# 使用
def transfer(from_acc, to_acc, amount):
    if from_acc.balance < amount:
        raise InsufficientFundsError('INSUFFICIENT_FUNDS', '餘額不足')
    # ...

with 語句與上下文管理器

# 內建支援:檔案、鎖、資料庫連線
with open('file.txt') as f:
    data = f.read()
# 自動 f.close(),即使發生異常

# 自定義:資料庫事務
class Transaction:
    def __enter__(self):
        self.conn = db.connect()
        return self.conn
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type:
            self.conn.rollback()
        else:
            self.conn.commit()
        self.conn.close()

with Transaction() as conn:
    conn.execute('...')

生產級錯誤處理檢查清單

  • [ ] 所有外部呼叫(網路、資料庫、檔案)包裝 try/except
  • [ ] 區分可重試錯誤(網路超時)與不可重試錯誤(資料錯誤)
  • [ ] 記錄完整堆疊追蹤:logging.exception() 或 traceback.format_exc()
  • [ ] 異常訊息不洩露敏感資訊(密碼、Token、PII)
  • [ ] 定義清晰的錯誤代碼體系,前端可對應顯示友善訊息
  • [ ] 關鍵資源使用 with/try/finally 確保釋放
  • [ ] 避免裸露 except:,至少 except Exception:
copyright © 萬盛學電腦網 all rights reserved