try/else,返回try b

2024-05-16 13:39:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中遇到了一个奇怪的行为。我在python帮助或SE上找不到关于此的信息,因此这里是:

def divide(x, y):
    print 'entering divide'
    try:
        return x/y
    except:
        print 'error'
    else:
        print 'no error'
    finally:
        print 'exit'

print divide(1, 1)
print divide(1, 0)

输出:

entering divide
exit
1
entering divide
error
exit
None

如果在try中返回值,python似乎不会进入else块。但是,它将始终位于finally块中。我真的不明白为什么。有人能帮我讲一下这个逻辑吗?

谢谢


Tags: nonone信息returndefexiterrorelse
3条回答

这种行为的原因是return内部的try

当发生异常时,finallyexcept块都在return之前执行。在没有异常发生的相反情况下,else运行,except不运行

按预期工作:

def divide(x, y):
    print 'entering divide'
    result = 0
    try:
        result = x/y
    except:
        print 'error'
    else:
        print 'no error'
    finally:
        print 'exit'

    return result

print divide(1, 1)
print divide(1, 0)

http://docs.python.org/reference/compound_stmts.html#the-try-statement

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.

未执行else块,因为在函数有机会执行之前,您已经离开了它。

但是,总是执行finally块(除非您拉断电源线或类似的东西)。

考虑这个(作为一个思想实验;请不要在实际代码中这样做):

def whoops():
    try:
        return True
    finally:
        return False

查看它返回的内容:

>>> whoops()
False

如果你感到困惑,你并不孤单。有些语言,比如C,会主动阻止您在finally子句中放置return语句。

相关问题 更多 >