Python 的 自定义异常层次

等级 5284 次按键

这创建了带有基类和派生类的自定义异常层次。像错误代码这样的自定义属性增强了错误处理。

Python 代码

# 定义继承自Exception的基础异常类
1class AppError(Exception):
# 构造函数接受消息和错误代码
2 def __init__(self, message, code):
# 用消息调用父构造函数
3 super().__init__(message)
# 将错误代码存储为属性
4 self.code = code
5
# 定义验证错误子类
6class ValidationError(AppError):
# 从AppError继承所有内容
7 pass
8
# 定义数据库错误子类
9class DatabaseError(AppError):
# 从AppError继承所有内容
10 pass
11
# 测试异常的try块
12try:
# 用消息和代码抛出验证错误
13 raise ValidationError("Invalid input", 400)
# 捕获任何AppError或其子类
14except AppError as e:
# 打印带代码和消息的格式化错误
15 print(f"Error [{e.code}]: {e}")

运行结果

Error [400]: Invalid input
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • _× 8
  • (× 8
  • )× 8
  • :× 7
  • "× 4
  • ,× 3
  • .× 3
  • {× 2
  • }× 2
  • [× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习