try / else with return in try block
PythonException HandlingPython Problem Overview
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
Python Solutions
Solution 1 - Python
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.
Solution 2 - Python
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)
Solution 3 - Python
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.
Solution 4 - Python
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)
, yourtry
clause does raise an exceptionZeroDivisionError
, so theelse
clause does not run. -
When you call
divide(1, 1)
, thetry
clause runs successfully, and returns. So theelse
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.
Solution 5 - Python
"return" ends the function and returns whatever you want it to return. So it won't go on of course. "finally" is always executed.