1.什么是异常?
异常是Python对象,表示一个错误。
2.为什么要做异常的处理?
程序发生异常时,会终止执行(异常发生后面的代码不执行了),为了解决这个问题,需要做异常的处理。
3.异常的分类? (万能的Exception基类)
4.异常处理的方法
捕捉异常和处理异常:使用try...except...
语句
把需要监控的代码放到try
语句块下面,把要处理的的方式放到except
语句块下面
4.1未做异常处理的报错(1.报错不是很友好;2.报错后的代码不执行了)
f = open('file.txt','r+')
f.write('hello world!')
print("程序报错后,测试是否运行~~~")
Traceback (most recent call last):
File "E:/chenxian_project/cx/study_cx/study_cx.py", line 2, in <module>
f = open('file.txt','r+')
FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
4.2.做了异常处理的报错(1.根据设置的报错信息提示;2.报错后,继续执行后面的代码)
try:
f = open('file.txt','r+')
f.write('hello world!')
except IOError as e:
print('Error:没有找到文件')
print("程序报错后,测试是否运行~~~")
Error:没有找到文件
程序报错后,测试是否运行~~~
5.try…except…else…的用法: try语句块没有发生错误,才执行else下面的代码
try:
for i in range(10):
int(i)
except IndexError as e:
print(e)
else:
print('***********')
***********
6.try…except…finally…的用法: 不管try语句块有没有发生错误,都要执行finally下面的代码
def dealwith_file():
try:
f = open('file.txt',encoding='utf-8')
for line in f:
int(line)
return True
except Exception as e:
print(e)
return False
finally:
'''不管try语句中的代码是否报错,都会执行finally分支中的代码'''
'''去完成一些连接操作的收尾工作'''
print('finally 被执行了')
f.close()
r = dealwith_file()
print(r)
finally 被执行了
True
7.使用raise抛出异常(为什么需要把异常抛出来呢?)
try:
f = open('file1.txt','r+')
f.write('hello world!')
except IOError as e:
print('Error:没有找到文件')
print("程序报错后,测试是否运行~~~")
raise e
Error:没有找到文件
程序报错后,测试是否运行~~~
Traceback (most recent call last):
File "E:/chenxian_project/cx/study_cx/study_cx.py", line 15, in <module>
raise e
File "E:/chenxian_project/cx/study_cx/study_cx.py", line 9, in <module>
f = open('file1.txt','r+')
FileNotFoundError: [Errno 2] No such file or directory: 'file1.txt