WoJ
WoJ

Reputation: 30015

Why can't I return when catching an exception with try:?

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

As 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

Answers (2)

Eric Lamas
Eric Lamas

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

Martijn Pieters
Martijn Pieters

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 or continue statement is executed in the try suite of a try...finally statement, the finally 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 the finally clause always executes, a return statement executed in the finally clause will always be the last one executed:

>>>
>>> def foo():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> foo()
'finally'

Upvotes: 6

Related Questions