Putting print
statements beforehand really, really helps:
def func1():
try:
print 'try statement in func1. after this return 1'
return 1
finally:
print 'after the try statement in func1, return 2'
return 2
def func2():
try:
print 'raise a value error'
raise ValueError()
except:
print 'an error has been raised! return 1!'
return 1
finally:
print 'okay after all that let\'s return 3'
return 3
print func1()
print func2()
This returns:
try statement in func1. after this return 1
after the try statement in func1, return 2
2
raise a value error
an error has been raised! return 1!
okay after all that let's return 3
3
You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1
in both functions.
A finally
block is always run, so the last thing to be returned in the function is whatever is returned in the finally block. In func1
, that's 2. In func2
, that's 3.