1.except 从上到下按顺序匹配
2.try语句正常运行后执行else 中的语句
3.finally 语句无论是否异常都会执行
try:
int('w3r')
except IndexError as e:
print('IndexError', e)
except ValueError as e:
print('ValueError')
except Exception as e:
print('Exception',e)
else:
print('else')
finally:
print('finally')
运行结果:
ValueError
finally
使用 raise 自动抛出异常
def db():
return False
def index():
try:
result = db()
if not result:
raise Exception('数据库处理错误')
except Exception as e:
error = str(e)
print(error)
index()
运行结果:
数据库处理错误
自定义错误
class myError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
try:
raise myError('有问题')
except myError as e:
print(e) # e对象的__str__()方法,获取返回
运行结果:
有问题
assert ,断言,用于强制用户服从,不服从就报错,可捕获,但是一般不捕获
print(111)
assert 1==2
print(666)
运行结果:
111
assert 1==2
AssertionError