Run code finally before returning in except

try:
       # Some Code.... 
except:       
       # Handling of exception
       return False
else:
       # execute if no exception
finally:
       print('done')
      # Execute before returning False incase of an exception

How do I get the code in finally to execute before returning False in except ?

I think you will have to resort to using a flag to defer the return:

did_except = False

try:
       ...
except:       
       did_except = True
else:
       ...
finally:
       print('done')
      
if did_except: 
    return False

This should already work. A return, break or continue acts the same as an exception for a finally block - it runs, then execution continues with those.

2 Likes

Indeed; this already works. This simple example:

def test_function():
    try:
        raise Exception()
    except Exception:
        print('except')
        return False
    finally:
        print('done')

test_function()

prints (in Python 3.9):

except
done

Note that the docs appear to imply this is only the case for the try block, though it clearly also applies for the except block:

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.’

1 Like