在Python中,你可以使用`raise`关键字来主动抛出异常。以下是一些基本的使用方法:
抛出内置异常类
try:
raise ValueError("This is a value error.")
except ValueError as e:
print(e)
抛出自定义异常类
class CustomException(Exception):
pass
try:
raise CustomException("This is a custom exception.")
except CustomException as e:
print(e)
在特定条件下抛出异常
class Person:
def __init__(self, name, age):
if 0 < age <= 150:
self.name = name
self.age = age
else:
raise AgeError(age)
class AgeError(Exception):
def __init__(self, age):
self.__age = age
def __str__(self):
return f"传入的年龄超出正常范围:age={self.__age}"
try:
p = Person("Alice", -1)
except AgeError as e:
print(e)
使用断言(assert)抛出异常
def fun(x):
if x > 5:
raise Exception(f"x 不能大于 5, x={x}")
try:
fun(7)
except Exception as e:
print(e)
自定义异常类
class MySQLError(Exception):
def __init__(self, error_info):
super().__init__(error_info)
try:
raise MySQLError("数据库连接失败")
except MySQLError as e:
print(e)
以上示例展示了如何在不同情况下使用`raise`关键字抛出异常,并展示了如何使用`try-except`语句来捕获和处理这些异常。