Skip to content

抛出异常与自定义异常 ​

raise语句 ​

python
def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age < 18:
        raise ValueError("Must be 18 or older")
    return age

try:
    check_age(15)
except ValueError as e:
    print(e)

自定义异常 ​

python
class InsufficientFundsError(Exception):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount = amount
        super().__init__(f"Balance {balance} < {amount}")

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

异常链 ​

python
try:
    # 原始错误
    raise ValueError("Original error")
except ValueError as e:
    # 包装并重新抛出
    raise RuntimeError("Wrapped error") from e

练习 ​

  1. 实现参数验证函数
  2. 创建自定义异常类
  3. 使用异常链

答案:第五章答案

下一节:上下文管理器

用心记录每一步成长