开发者

try / else with return in try block

I came across a strange behavior in python. I could not find information about this in the python help or on SE so here it is:

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)

the output:

entering divide
exit
1
entering divide
error
exit
None

It seems that python will not go inside the else block if a value is returned in the try. However, it will always go in the finally block. I don't really understand why. Can someone help me with this log开发者_StackOverflow社区ic?

thanks


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.


The reason for this behaviour is because of the return inside try.

When an exception occurs, both finally and except blocks execute before return. Otherwise only finally executes and else doesn't because the function has already returned.

This works as expected:

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)


The else block isn't executed because you have left the function before it got a chance to do so.

However, the finally block is always executed (unless you yank the power cord or something like that).

Consider this (as a thought experiment; please don't do that in real code):

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

See what it returns:

>>> whoops()
False

If you find this confusing, you're not alone. Some languages like C# actively prevent you from placing a return statement in a finally clause.


Why doesn't the else clause run?

A else clause is useful for code that must be executed if the try clause does not raise an exception.

  • When you call divide(1, 0), your try clause does raise an exception ZeroDivisionError, so the else clause does not run.

  • When you call divide(1, 1), the try clause runs successfully, and returns. So the else clause is never reached.


Why does the finally clause always run?

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

See above.


Reference https://docs.python.org/3.5/tutorial/errors.html


"return" ends the function and returns whatever you want it to return. So it won't go on of course. "finally" is always executed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜