return "a" or "b"

2019/01/21 19:31
阅读数 0

按照惯例,我们先看一下例子,如果知道答案就可以节约一下大家的几分钟时间.

例子

example 00

  
    
  
  
  1. def test():

  2.    try:

  3.        return "a"

  4.    finally:

  5.        return "b"


  6. print(test())

example 01

  
    
  
  
  1. def test():

  2.    try:

  3.        a = 1/0

  4.    except Exception as e:

  5.        return "a"

  6.    finally:

  7.        return "b"


  8. print(test())

example 00 和 example 01 的正确答案分别为: b , b

原因

原因在官方文档中写的清清楚楚,看一下官方原文:

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in an except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

重点在加粗的那句话,大意就是无论在 try 语句中执行 break, continue 或者 return 什么,finally 语句最终一定会被执行,所以在实际应用中 finally 通常被用来释放外部资源,比如 文件或者网络连接,无论资源是否使用成功.

本文分享自微信公众号 - 桃子的学习笔记(LeeTaoThinks)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部