Python/gloss python try finally
来自菜鸟教程
<languages />
Python最后尝试
最后尝试
The
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()
程序可以继续运行,而无需打开文件对象。