自定义异常类的设计
如何在 Python 中自定义异常类?自定义异常应该继承哪个基类?请给出最佳实践。
回答
苦行僧
自定义异常应继承 Exception(或其子类),不建议继承 BaseException(因为会捕获到 SystemExit、KeyboardInterrupt)。
class PaymentError(Exception):
"""支付相关异常基类"""
pass
class InsufficientBalanceError(PaymentError):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(
f'余额不足:需要 {amount},当前余额 {balance}'
)
最佳实践:
- 从
Exception继承 - 使用有意义的类名(以 Error 结尾)
- 提供层次化的异常体系
- 实现
__init__传递有用的上下文信息