Python Try Finally 异常处理
Try Finally 异常处理
finally
块,如果指定,无论 try 块是否引发错误,都会执行。
实例
try:
print(x)
except:
print("Something went
wrong")
finally:
print("The 'try except' is finished")
亲自试一试 »
这对于关闭对象和清理资源很有用:
实例
尝试打开并写入一个不可写的文件:
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went
wrong when writing to the file")
finally:
f.close()
亲自试一试 »
程序可以继续,而无需打开文件对象。