处理异常的框架
try:
file=open("","r")
..
file.close()
except FileNotFoundError:
print("未找到")
except NameError:
print("转换失败")
except:
print("处理其他所有异常")
else:
print("没有异常执行这里")
finally: #无论有没有异常 都会执行
print("都会执行")
弹出异常
def makename(name):
if name.find("SB")!=-1:
print(name)
raise NameError
print("OK")
return name
try:
print(makename("SBSB"))
except:
print("123321error")
在测试中,因为弹出了异常,所以输出123321error
with as的用法
#########
with open(r"E:\PY111\new.txt","r") as file:
for line in file:
print(line,end="")
##其中with as 会自动进行file.close()