加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

理解python尝试catch else finally子句行为

发布时间:2020-12-20 12:22:59 所属栏目:Python 来源:网络整理
导读:Python 2.6.5(r265:79063,2012年10月1日,22:07:21) 我有这个: def f(): try: print "a" return except: print "b" else: print "c" finally: print "d"f() 这给出了: ad 而不是预期的 a c d 如果我评论退货,那么我会得到 a c d 我怎么记得python中的这
Python 2.6.5(r265:79063,2012年10月1日,22:07:21)

我有这个:

def f():
    try:
        print "a"
        return
    except:
        print "b"
    else:
        print "c"
    finally:
        print "d"
f()

这给出了:

a
d

而不是预期的

a 
c 
d

如果我评论退货,那么我会得到

a 
c 
d

我怎么记得python中的这种行为?

解决方法

如有疑问,请咨询 the docs:

The optional else clause is executed if and when control flows off the end of the try clause

Currently,control “flows off the end” except in the case of an exception or the execution of a return,continue,or break statement.

由于您从try块的主体返回,因此else将不会被执行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读