小码哥的IT人生

Python finally 关键字

Python基础 2022-06-06 16:26:07小码哥的IT人生shichen

Python finally 关键字

实例

无论 try 块是否引发错误,都将始终执行 finally 块:

try:
  x > 3
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
finally:
  print("The try...except block is finished")

完整实例:

try:
  x > 3
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
finally:
  print("The try...except block is finished")

定义和用法

finally 关键字在 try ... except 块中使用。它定义了一个代码块,当 try...except...else 块结束时,该代码块将运行。

无论 try 块是否引发错误,都将执行 finally 块。

这对于关闭对象和清理资源很有用。

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024