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__ 接受资源类型和 id
13 def __init__(self, resource: str, id: str):
# 存储资源类型
14 self.resource = resource
# 存储缺失的 id
15 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 的数据调用 process
24 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

Python 等级 5 的更多代码示例

← 返回 Python 打字练习