用try,except处理异常
try:
age=input('1>>: ')
int(age)
num2=input('2>>: ')
int(num2)
l=[]
l[10000]
dic={}
dic['name']
except KeyError as e:
print(e)
except ValueError as e:
print('===>',e)
except IndexError as e:
print('---->',e)
print('11111111111111111')
while True:
try:
age=input('1>>: ')
int(age)
break
except Exception as e:
print('请重新输入',e)
print('11111111111111111')
异常的else,finally结构
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
except Exception as e:
print(e)
else:
print('try内代码块没有异常则执行我')
finally:
print('无论异常与否,都会执行该模块')
print(1111111111111)
print(22222222222)
print(33333333333)
自己定制异常类
class EgonException(BaseException):
def __init__(self,msg):
self.msg=msg
raise TypeError('类型错误')
raise EgonException('自己定制的异常')
print(EgonException('自己定制的异常'))
assert断言
def test1():
'一堆逻辑'
res=1
return 1
res1=test1()
assert res1 == 2
if res1 != 2:
raise AssertionError