Python 的 自定义异常层次结构
等级 5714 次按键
这创建了一个自定义异常层次结构,包含基类AppError和专门的子类。
Python 代码
# class AppError(Exception) 是基础自定义异常1class AppError(Exception): # __init__ 接受消息和可选的错误代码2 def __init__(self, message: str, code: int = 500): # 将消息存储为实例属性3 self.message = message # 存储 HTTP 风格的错误代码4 self.code = code # 调用父类 Exception 构造函数5 super().__init__(self.message)6 # class ValidationError(AppError) 用于验证失败7class ValidationError(AppError): # __init__ 接受字段名和错误消息8 def __init__(self, field: str, message: str): # 存储验证失败的字段9 self.field = field # 使用格式化消息和 400 代码调用父类10 super().__init__(f"{field}: {message}", code=400)11 # class NotFoundError(AppError) 用于缺失资源12class NotFoundError(AppError): # __init__ 接受资源类型和 id13 def __init__(self, resource: str, id: str): # 存储资源类型14 self.resource = resource # 存储缺失的 id15 self.id = id # 使用格式化消息和 404 代码调用父类16 super().__init__(f"{resource} with id '{id}' not found", code=404)17 # def process 演示抛出自定义异常18def process(data): # 检查 name 字段是否缺失19 if not data.get("name"): # 为缺失的 name 抛出验证错误20 raise ValidationError("name", "is required") # 只有name存在时才会执行到这里,抛出NotFoundError(演示用)21 raise NotFoundError("User", data.get("id", "unknown"))22 # try 块捕获自定义异常23try: # 用缺少 name 的数据调用 process24 process({"id": "123"})# 捕获任何 AppError 或其子类25except AppError as e: # 打印带代码和消息的错误26 print(f"Error [{e.code}]: {e.message}")运行结果
Error [400]: name: is required
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
_× 24"× 22:× 19(× 19)× 19.× 13,× 11=× 8{× 7}× 7