异常:
程序运行时的错误,对应一个Python对象。
try:
语句块
except 异常1 as 错误原因:
出现异常1后的处理代码
except 异常2 as 错误原因:
出现异常2后的处理代码
#在程序运行时,解释器尝试执行try语句块中的所有代码。
try:alist = [0,1,2]print(alist[3])print("try语句块继续执行中。。。。。")#如果语句块被执行完后没有异常发生,就会忽略except后的代码。
#当某个except所指定的异常发生后,会忽略try子句中剩余的语句,直接跳转到对应异常的处理代码处执行。
except IndexError as e:print(e)print("异常已经处理了")
print("程序继续执行中。。。。")
try:alist = [0,1,2]print(alist[2])print("try语句块继续执行中。。。。。")
except IndexError as e:print(e)print("异常已经处理了")
print("程序继续执行中。。。。")
Python中常见的异常
finally子句:
无论异常是否发生,都会执行
finally语句块经常用于关闭资源等清理工作。
try:print("try start")f = open(r"D:\code1\pythontest\mypython.txt","w")print(f.read())print("try end")
except IOError as e:print("except start")print(e)
finally:print("finally start")f.close()
try:print("try start")f = open(r"D:\code1\pythontest\mypython.txt")print(f.read())print("try end")
except IOError as e:print("except start")print(e)
finally:print("finally start")f.close()
个人公众号