- raise 指定要抛出的异常。
- 对应参数必须是异常的实例或是异常的类(Exception)
例:
def fun(x):
if x > 5:
raise Exception(f"x 不能大于 5,x={x}")
"""
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in fun
Exception: x 不能大于 5,x=7
"""
1.2 assert
assert condition
# condition 为真,不做任何事情
# condition 为假,抛出AssertionError异常
# 等价于:
if not condition:
raise AssertionError()
2. 自定义异常
- 自定义类异常必须继承 Exception
自定义异常:
class MySQLError(Exception):
def __init__(self, error_info):
super(MySQLError, self).__init__(error_info)
self.error_info = error_info
def __str__(self):
return self.error_inf
使用自定义异常:
try:
raise MySQLError('异常')
except MySQLError as e:
print(e)



