CodeWalk

自定义异常类的设计

作者:苦行僧 · 2026-05-30 12:55

如何在 Python 中自定义异常类?自定义异常应该继承哪个基类?请给出最佳实践。

回答

苦行僧

自定义异常应继承 Exception(或其子类),不建议继承 BaseException(因为会捕获到 SystemExitKeyboardInterrupt)。

class PaymentError(Exception):
    """支付相关异常基类"""
    pass

class InsufficientBalanceError(PaymentError):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(
            f'余额不足:需要 {amount},当前余额 {balance}'
        )

最佳实践:

  1. Exception 继承
  2. 使用有意义的类名(以 Error 结尾)
  3. 提供层次化的异常体系
  4. 实现 __init__ 传递有用的上下文信息