一、异常类型
1、属性错误AttributeError
2、索引错误IndexError
3、数值错误’ValueError
4、类型错误TypeError
5、名称错误NameError
6、除零错误ZeroDivisionError
二、捕获异常
程序执行时遇到异常会中断,当需要在遇到异常时做出一些处理而不是中断程序
1、try…except…
(1)
try:
lsm=int(input('lsm='))
print(6/lsm)
except:
print("can't divide 0")
>>>lsm=0
>>>can't divide 0
(2)设置捕获特定的异常
try:
lsm=int(input('lsm='))
print(6/lsm)
except(ZeroDivisionError):#指定捕获的异常类型
print("can't divide 0")
>>>lsm=0
>>>can't divide 0
2、try…except…else
else后面的代码是没发生异常时执行
(1)
try:
lsm=6/2
except(ZeroDivisionError,NameError) as e:#指定捕获的异常类型
print(e)
else:
print(lsm)
>>>3.0
(2)
try:
lsm=6/0
except(ZeroDivisionError,NameError) as e:#指定捕获的异常类型
print(e)
else:
print(lsm)
>>>division by zero
(3)可以多个except分别处理多个异常
try:
lsm=6/c
except(ZeroDivisionError) as e:#指定捕获的异常类型
print(e)
except(NameError) as n:#指定捕获的异常类型
print(n)
else:
print(lsm)
>>>name 'c' is not defined
3、finally无论程序是否有异常,都会执行的部分
(1)
try:
lsm=6/c
except(ZeroDivisionError) as e:#指定捕获的异常类型
print(e)
except(NameError) as n:#指定捕获的异常类型
print(n)
else:
print(lsm)
finally:
print("i'm finally")
>>>name 'c' is not defined
>>>i'm finally
(2)
try:
lsm=6/2
except(ZeroDivisionError) as e:#指定捕获的异常类型
print(e)
except(NameError) as n:#指定捕获的异常类型
print(n)
else:
print(lsm)
finally:
print("i'm finally")
>>>3.0
>>>i'm finally
三、assert关键字
assert Expression, e
try:
lsm=input('input a string of length greater than 4:')
assert len(lsm)>=4,'string is short'
except AssertionError:
print('string is short')
lsm=lsm+"_"*(4-len(lsm))
finally:
print(lsm)
>>>input a string of length greater than 4:lsm
>>>string is short
>>>lsm_
三、raise关键字,主动抛出异常
raise ValueError( ' This isa value error !' )