1.1什么是异常?
异常时程序发生错误的信号,一旦程序出错机会产生一种类型的异常,
1.2为什么要处理异常?
为了保证程序的健壮性
1.3怎么处理异常?
语法错误:程序运行前就应该解决
逻辑错误:try…except
1.4五种异常处理语法:
异常处理一:
try:
print(x)
print('hello')
l=[1,2,3]
l=[0]
except NameErroras e:
print('按照这个方法处理')
print('other code...')
异常处理二:
try:
# print(x)
print('hello')
l=[1,2,3]
l=[0]
dic={'x':111}
dic['e']
except NameErroras e:
print('按照这个方法处理')
except IndexErroras e:
print('index error')
except KeyErroras e:
print('key error')
异常处理三:
try:
# print(x)
print('hello')
l=[1,2,3]
l=[0]
dic={'x':111}
dic['e']
except (NameError,IndexError,KeyError)as e:
print(e)
异常处理四:
try:
# print(x)
print('hello')
l=[1,2,3]
l=[0]
dic={'x':111}
dic['e']
except Exceptionas e:
print(e)
异常处理五:
try:
# print(x)
print('hello')
l=[1,2,3]
l=[0]
dic={'x':111}
dic['e']
except NameErroras e:
print('name error')
except IndexErroras e:
print('index error')
except Exceptionas e:
print(e)
异常处理六:
try:
# print(x)
print('hello')
l=[1,2,3]
l=[0]
dic={'x':111}
dic['e']
except NameErroras e:
print('name error')
except IndexErroras e:
print('index error')
except Exceptionas e:
print(e)
else:
print('当被检测代码块没有异常时执行')
finally:
回收系统资源