try—except—else—finally
出现报错时,except捕获异常,并显示错误原因,如果没有错误,不执行except,而是执行else,finally是无论对错都要执行.加粗样式
import time
try:
f = open("text1.txt")
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(1)
print(content)
except Exception as error_1:
print("1产生错误:%s"%error_1)
else:
print("程序正常")
finally:
f.close()
print("关闭文件")
except Exception as error_2:
print("2产生错误:%s"%error_2)