Reputation: 30015
I would like to return from a function upon some conditions when catching an exception:
def myfunc():
try:
a = 1
except:
pass
else:
if a == 1:
return a
finally:
return 100
x = myfunc()
print(x)
My expectation for the code above was that
try
succeeds (no exception raised)else
where the condition is meta
from function, the rest of the code is not ranAs you can imagine, I get as a result 100
, which means that the finally
clause was assessed.
Since I am obviously missing something I ran this though a debugger and I indeed reach the return a
line but do not actually return at that point.
Upvotes: 1
Views: 103
Reputation: 129
The finally statement is always executed in as per the try statement documentation. For your function you may wish to use an "else if"
def myfunc():
try:
a = 1
except:
pass
elif: a == 1:
return a
else:
return 100
x = myfunc()
print(x)
Upvotes: 1
Reputation: 1123350
finally
is always executed. You are returning just fine, it is just that you misunderstood what the finally
suite does.
From the try
statement documentation:
When a
return
,break
orcontinue
statement is executed in thetry
suite of atry...finally
statement, thefinally
clause is also executed ‘on the way out.’
In this context, the except
and else
handlers are part of the try
suite still.
The finally
suite is meant as a clean-up handler; once you enter the try
suite, finally
is guaranteed to be executed, no matter what happens. This can also mean you can alter what is returned. This is explicitly documented:
The return value of a function is determined by the last
return
statement executed. Since thefinally
clause always executes, areturn
statement executed in thefinally
clause will always be the last one executed:>>> >>> def foo(): ... try: ... return 'try' ... finally: ... return 'finally' ... >>> foo() 'finally'
Upvotes: 6