文章目录
- import json try: config = json.load(open(‘config.json’)) except FileNotFoundError as fnf_error: raise RuntimeError(“配置文件加载失败”) from fnf_error # 错误输出显示关联关系 # RuntimeError: 配置文件加载失败 # The above exception was the direct cause of…
- class NetworkTimeout(Exception): “””自定义网络超时异常””” def __init__(self, host, timeout): self.host = host self.timeout = timeout super().__init__(f”连接 {host} 超时({timeout}s)”) # 触发自定义异常 if response_time > 30: raise NetworkTimeout(“api.example.com”, 30)
- def divide(a, b): if b == 0: raise ZeroDivisionError(“除数不能为零”) return a / b
- def fetch_data(url): response = requests.get(url) if 400 <= response.status_code < 500: raise ClientError(response.status_code, response.text) elif response.status_code >= 500: raise ServerError(response.status_code) return response.json()
- def validate_user(user): if not user.get(‘username’): raise ValueError(“用户名必填”) if len(user[‘password’]) < 8: raise SecurityError(“密码至少8位”) if not re.match(r”[^@]+@[^@]+.[^@]+”, user[’email’]): raise FormatError(“邮箱格式无效”) return True
- class Transaction: def __enter__(self): if not self.conn.is_valid(): raise ConnectionError(“数据库连接失效”) return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: self.rollback() raise TransactionError(“事务执行失败”) from exc_val self.commit()
目录
- 一、核心语法解析
- 1.1 基础语法形式
- 1.2 完整语法结构
- 二、基础用法场景
- 2.1 触发内置异常
- 三、高级用法技巧
- 3.1 异常链(Exception Chaining)
- 3.2 自定义异常触发python
- 四、特殊形式详解
- 4.1 无异常类型抛出
- 4.2 异常参数传递
- 五、常见使用模式
- 5.1 防御式编程
- 5.2 API 错误处理
- 六、最佳实践指南
- 6.1 异常类型选择原则
- 6.2 异常消息规范
- 七、注意事项
- 八、综合应用示例
- 8.1 数据验证链
- 8.2 上下文管理器
- 总结
raise [异常类型[(参数)]]
用法说明:
- 只能存在于异常处理块(
except或finally)内部 - 自动重新抛出当前捕获的异常
- 保持原始异常堆栈信息
raise [异常类型[(参数)]] [from 原因]
# 参数校验场景
def calculate_square(n):
if not isinstance(n, (int, float)):
raise TypeError("必须传入数值类型")
return n ** 2
# 调用示例
calculate_square("5") # 触发 TypeError
import json
try:
config = json.load(open('config.json'))
except FileNotFoundError as fnf_error:
raise RuntimeError("配置文件加载失败") from fnf_error
# 错误输出显示关联关系
# RuntimeError: 配置文件加载失败
# The above exception was the direct cause of...
class NetworkTimeout(Exception):
"""自定义网络超时异常"""
def __init__(self, host, timeout):
self.host = host
self.timeout = timeout
super().__init__(f"连接 {host} 超时({timeout}s)")
# 触发自定义异常
if response_time > 30:
raise NetworkTimeout("api.example.com", 30)
def deprecated_feature():
raise "该功能已废弃" # ❌ 错误!必须抛出 Exception 实例
# 正确做法
def deprecated_feature():
raise DeprecationWarning("该功能已废弃")
try:
raise ValueError("无效输入", 404, {"detail": "ID不合法"})
except ValueError as e:
print(e.args) # ('无效输入', 404, {'detail': 'ID不合法'})
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除数不能为零")
return a / b
def fetch_data(url):
response = requests.get(url)
if 400 <= response.status_code < 500:
raise ClientError(response.status_code, response.text)
elif response.status_code >= 500:
raise ServerError(response.status_code)
return response.json()
| 错误场景 | 推荐异常类型 |
|---|---|
| 参数类型错误 | TypeError |
| 参数值无效 | ValueError |
| 文件操作错误 | IOError |
| 业务规则违反 | 自定义异常 |
# 不推荐
raise ValueError("错误发生")
# 推荐格式
raise ValueError(f"参数 {param} 的值 {value} 超出有效范围(允许范围:{min}~{max})")
from 参数使用
# 显示原始异常原因 raise ParsingError from original_error
性能考量
- 避免在循环中频繁抛出异常
- 异常处理耗时是条件判断的
10-100倍
调试辅助
# 打印完整堆栈
import traceback
try:
risky_call()
except:
traceback.print_exc()
raise # 重新抛出
def validate_user(user):
if not user.get('username'):
raise ValueError("用户名必填")
if len(user['password']) < 8:
raise SecurityError("密码至少8位")
if not re.match(r"[^@]+@[^@]+.[^@]+", user['email']):
raise FormatError("邮箱格式无效")
return True
class Transaction:
def __enter__(self):
if not self.conn.is_valid():
raise ConnectionError("数据库连接失效")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
self.rollback()
raise TransactionError("事务执行失败") from exc_val
self.commit()
以上为个人经验,希望能给大家一个参考,也希望大家多多支持风君子博客。
您可能感兴趣的文章:
- python中自定义异常/raise关键字抛出异常的案例解析
- Python中raise用法简单实例(超级详细,看了无师自通)
- python主动抛出异常raise的方法实现
- python如何使用raise抛出自定义异常
- python 中raise用法