try / else with return in try block

Question:

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 logic?

thanks

Asked By: Simon Bergot

||

Answers:

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.

Answered By: wRAR

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

Answered By: Musaab

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)
Answered By: Saul

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.

Answered By: Tim Pietzcker

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

Answered By: kgf3JfUtW
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.