異常處理是強健程式的基石。本文系統講解 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 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/exceptlogging.exception() 或 traceback.format_exc()with/try/finally 確保釋放except:,至少 except Exception: