异常
我们常见的代码错误后 会出现此类异常
SyntaxError:语法错误
AttributeError:属性错误
IndexError:索引错误
TypeError:类型错误NameError:变量名不存在错误
KeyError:映射中不存在的关键字(键)的错误
ValueError:值错误
异常本身就是一个类,所有的类都继承于BaseException类
SystemExit:退出异常
KeyboarInterrupt:键盘打断
GeneratorExit:生成器退出
Exception:普通异常 --------- 上面的常见异常都是Exception的子类
查看异常结构
print(help(NameError))
错误回溯
点击蓝色文字
print(a)
异常捕捉
语法结构
try:# 可能出现错误的代码
except Exception(可以写其他异常类型,如果多个异常类型,需放元组里) as e:# 捕捉到异常的处理方案
else:# 没有异常时执行
finally:# 不管是否出现异常都会执行
简单使用
try:print(a)
except Exception as e:print(e)# name 'a' is not defined
try:print(1)
except Exception as e:print(e)
else:print(2)
finally:print(3)# 1
# 2
# 3
try:print(a)
except Exception as e:print(e)
else:print(2)
finally:print(3)# name 'a' is not defined
# 3
raise
主动抛出异常
try:num = input('请输入一个数值:')if not num.isdigit():raise ValueError('num必须为纯数字')print(f'数字是{num}')except Exception as e:print(e)# 如果输入 1234 那么就会输出 数字是1234
# 如果输入 qwer 那么就会输出 num必须为纯数字
自定义异常 -- 小游戏
def number():print('小游戏')print('请输入1~10的数字字母,如果长度正确,则游戏胜利,否则输了')a = input('请输入:')if len(a) == 7:print('游戏胜利')else:raise Exception('游戏失败')while True:try:number()breakexcept Exception as e:print(e)
assert
断言,强制要求一个条件满足
assert 条件, '抛出自定义异常'
def user():assert 10 < 1, '错误,10是大于1的'print('123') # 只有上面满足,这行代码才会执行try:user()
except Exception as e:print(e)# 错误,10是大于1的
def func(passwd):assert 12 > len(passwd) > 6, '密码过长或过短'print('密码正常')try:a = input('请输入密码:')func(a)print(123) # 上面没通过,这一行也不会执行
except Exception as e:print(e)# 输入 7-11位数才正常,否则抛出异常