本文目录导读:

在Python中,使用raise关键字可以主动抛出异常,以下是各种常见的用法和案例:
基础语法
# 基本格式
raise Exception("错误信息")
抛出内置异常
# 抛出不同类型的异常
raise ValueError("参数值错误")
raise TypeError("类型不匹配")
raise KeyError("键不存在")
raise IndexError("索引越界")
raise ZeroDivisionError("除数不能为零")
raise FileNotFoundError("文件未找到")
实际应用案例
案例1:参数验证
def divide(a, b):
if b == 0:
raise ValueError("除数不能为0")
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("参数必须是数字")
return a / b
# 测试
try:
result = divide(10, 0)
except ValueError as e:
print(f"值错误: {e}")
案例2:用户登录验证
class UserNotExistError(Exception):
pass
def login(username, password):
users = {"admin": "123456"}
if username not in users:
raise UserNotExistError(f"用户 {username} 不存在")
if users[username] != password:
raise PermissionError("密码错误")
return "登录成功"
try:
result = login("admin", "wrong")
except UserNotExistError as e:
print(f"用户不存在: {e}")
except PermissionError as e:
print(f"权限错误: {e}")
案例3:数据验证
def validate_age(age):
if not isinstance(age, int):
raise TypeError("年龄必须是整数")
if age < 0 or age > 150:
raise ValueError("年龄必须在0-150之间")
return f"年龄验证通过: {age}岁"
# 多种异常处理
try:
validate_age("twenty")
except (TypeError, ValueError) as e:
print(f"验证失败: {e}")
自定义异常类
class BusinessException(Exception):
"""自定义业务异常"""
def __init__(self, code, message):
self.code = code
self.message = message
super().__init__(self.message)
class OrderException(BusinessException):
"""订单相关异常"""
pass
def create_order(amount, user_id):
if amount <= 0:
raise OrderException(1001, "订单金额必须大于0")
if user_id is None:
raise OrderException(1002, "用户ID不能为空")
return "订单创建成功"
try:
create_order(-100, None)
except OrderException as e:
print(f"业务错误 [code={e.code}]: {e.message}")
重新抛出异常
def process_data(data):
try:
result = 1 / data
return result
except ZeroDivisionError:
print("捕获到除零错误,重新抛出...")
raise # 重新抛出当前异常
except Exception as e:
print(f"发生错误: {e}")
raise ValueError("数据处理失败") from e # 链式异常
# 测试
try:
process_data(0)
except ZeroDivisionError:
print("外部处理除零错误")
assert 断言(简化的raise)
def calculate_discount(price, discount):
assert price > 0, "价格必须大于0"
assert 0 <= discount <= 1, "折扣必须在0-1之间"
return price * (1 - discount)
try:
calculate_discount(-100, 0.5)
except AssertionError as e:
print(f"断言错误: {e}")
条件判断主动抛错
def transfer_money(balance, amount):
# 多个条件判断
conditions = {
"余额不足": balance < amount,
"金额超过限额": amount > 10000,
"金额无效": amount <= 0
}
for error_msg, condition in conditions.items():
if condition:
raise ValueError(error_msg)
return balance - amount
try:
transfer_money(1000, 20000)
except ValueError as e:
print(f"转账失败: {e}")
在循环中抛错
def find_user(users, target_id):
for user in users:
if user["id"] == target_id:
return user["name"]
raise KeyError(f"未找到用户ID: {target_id}")
users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
try:
name = find_user(users, 3)
except KeyError as e:
print(f"查找失败: {e}")
最佳实践建议
- 选择合适的异常类型:尽量使用Python内置的异常类型
- 提供明确的错误信息:让人快速理解问题
- 不要滥用异常:正常流程控制避免使用异常
- 保持异常粒度适中:不要过于笼统或过于精细
- 合理使用自定义异常:复杂业务场景下使用
这些案例涵盖了Python中主动抛出异常的大部分场景,掌握这些能帮助你写出更健壮的代码。