From the Python documentation

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):

So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.

In your particular case, func1() returns 2 and func2() returns 3, as these are values returned in the finally blocks.

Answer from lejlot on Stack Overflow
Top answer
1 of 4
242

From the Python documentation

A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement. A more complicated example (having except and finally clauses in the same try statement works as of Python 2.5):

So once the try/except block is left using return, which would set the return value to given - finally blocks will always execute, and should be used to free resources etc. while using there another return - overwrites the original one.

In your particular case, func1() returns 2 and func2() returns 3, as these are values returned in the finally blocks.

2 of 4
61

It will always go to the finally block, so it will ignore the return in the try and except. If you would have a return above the try and except, it would return that value.

def func1():
    try:
        return 1 # ignoring the return
    finally:
        return 2 # returns this return

def func2():
    try:
        raise ValueError()
    except:
        # is going to this exception block, but ignores the return because it needs to go to the finally
        return 1
    finally:
        return 3

def func3():
    return 0 # finds a return here, before the try except and finally block, so it will use this return 
    try:
        raise ValueError()
    except:
        return 1
    finally:
        return 3


func1() # returns 2
func2() # returns 3
func3() # returns 0
🌐
Python
peps.python.org › pep-0765
PEP 765 – Disallow return/break/continue that exit a finally block | peps.python.org
November 15, 2024 - If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement. Both of these behaviours cause confusion, but the first is particularly dangerous because a swallowed exception is more likely to slip through testing, than an incorrect return value. In 2019, PEP 601 proposed to change Python to emit a SyntaxWarning for a few releases and then turn it into a SyntaxError.
Discussions

Why aren't exceptions re-raised if `finally` contains a `return/break/continue`?
From the docs: If the finally clause executes a break, continue or return statement, exceptions are not re-raised. Why is this? I would have thought that an exception would take priority over a return/break/continue statement, especially since PEP8 explicitly discourages the use of control ... More on discuss.python.org
🌐 discuss.python.org
10
0
August 11, 2022
Jump statement in try except finally block
Hi all, can someone say why this is stuck in a infinite loop? Code while True: print("why is this happening") try: break finally: continue Output why is this happening why is this happening why is this happening ... More on discuss.python.org
🌐 discuss.python.org
17
2
June 29, 2024
Today I learned that finally executes after return
They do not. The run before returning. At the end of the function block. You are confused by the order of printing? That's because your function is not returning 'console.log("returning"), 1'. It is returning the result of evaluating that expression. The only reason you see '2' is because javascript lets you override the return value that's already been calculated. Most languages don't do this. Your function compiles to this: func { console.log("returning"); set _magical_return_variable = 1; console.log("finally"); set _magical_return_variable = 2; return; // Return is here. After the calculation. After the finally. } More on reddit.com
🌐 r/programminghorror
32
148
February 8, 2024
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 ? More on discuss.python.org
🌐 discuss.python.org
3
0
December 6, 2023
🌐
Reddit
reddit.com › r/learnpython › what happens when you use try and except statements in a function that both have a return statement in them but you also have a finally statement?
r/learnpython on Reddit: What happens when you use try and except statements in a function that both have a return statement in them BUT you also have a finally statement?
May 30, 2023 -

Ok, that was an awful title and I'm sorry... but it's hard to phrase! My question overall is, if we use a try statement in a function (and let's imagine it works, we don't end up having to handle any exceptions) and there is a return statement in this try-block. Won't that cause us to leave the function? Since, we are returning control back to main, let's say.

But, we have a finally statement in our function to. It might do something trivial like print something. Does this get executed even though we should have hit return?

Now, I have tested this. And what it seems to do is reach the return statement, ignore it, carry out the finally statement and then go back to the return. But I would like to know if I am understanding this correctly.

🌐
Python.org
discuss.python.org › python help
Why aren't exceptions re-raised if `finally` contains a `return/break/continue`? - Python Help - Discussions on Python.org
August 11, 2022 - From the docs: If the finally clause executes a break, continue or return statement, exceptions are not re-raised. Why is this? I would have thought that an exception would take priority over a return/break/continue statement, especially since ...
🌐
Python.org
discuss.python.org › python help
Jump statement in try except finally block - Python Help - Discussions on Python.org
June 29, 2024 - Hi all, can someone say why this is stuck in a infinite loop? Code while True: print("why is this happening") try: break finally: continue Output why is this happening why is this happening why is this happening ...
🌐
Medium
medium.com › analytics-vidhya › do-you-really-understand-try-finally-in-python-110cee4c1a8
Do You Really Understand Try & Finally in Python? | by Aravind Ramalingam | Analytics Vidhya | Medium
March 14, 2024 - # The try block has return statement & final block has only print statement def example_2(): try: val = 1 print(f"Print: Try Block - {val}") return f"Return: Try Block - {val}" finally: val = val + 1 print(f"Print: Finally Block - {val}") example_2() ... Function example_2 is where things get a bit tricky, the return statement in try-block is executed after the final-block but the value of the variable val returned is not affected by the changes made in the final-block.
🌐
Plain English
python.plainenglish.io › executing-code-after-a-return-statement-in-python-functions-887dba33004d
Executing Code AFTER A Return Statement In Python Functions | by Liu Zuo Lin | Python in Plain English
August 10, 2022 - In Python functions, nothing happens after the return statement is executed. def stuff(): print("a") return "stuff" print("b")stuff() If we run this function, only "a" is printed.
Find elsewhere
🌐
Raravind
raravind.com › blog › data-science › do-you-really-understand-try-finally-in-python
Do You Really Understand Try & Finally in Python?
April 18, 2021 - # The try block has return statement & final block has only print statement def example_2(): try: val = 1 print(f"Print: Try Block - ") return f"Return: Try Block - " finally: val = val + 1 print(f"Print: Finally Block - ") example_2() Function example_2 is where things get a bit tricky, the returnstatement in try-block is executed after the final-block but the value of the variable valreturned is not affected by the changes made in the final-block.
🌐
Real Python
realpython.com › lessons › python-return-try-finally
Using return With try and finally Blocks (Video) – Real Python
00:32 Simply put, when you use a return statement inside a try statement that has a finally clause, that finally clause is always executed before the return statement. Specifically, this means that the finally clause will always be executed ...
Published   August 10, 2021
🌐
Reddit
reddit.com › r/programminghorror › today i learned that finally executes after return
r/programminghorror on Reddit: Today I learned that finally executes after return
February 8, 2024 - Here, you can use the return keyword again which will store a new return value and then start exiting code blocks again. If you don't return again inside the finally block, then as soon as the finally block finishes, it continues exiting code blocks.
🌐
GeeksforGeeks
geeksforgeeks.org › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception.
Published   September 8, 2024
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
If the try statement reaches a break, continue or return statement, the finally clause will execute just prior to the break, continue or return statement’s execution.
🌐
Python
peps.python.org › pep-0601
PEP 601 – Forbid return/break/continue breaking out of finally | peps.python.org
August 26, 2019 - continue is currently not supported in a finally in Python 3.7 (due to implementation issues) and the proposal is to not add support for it in Python 3.8. For return and break the proposal is to deprecate their use in Python 3.9, emit a compilation warning in Python 3.10 and then forbid their use after that.
🌐
Quora
quora.com › How-does-the-finally-clause-work-in-Pythons-try-except-blocks
How does the finally clause work in Python's try-except blocks? - Quora
... You just do that. This is the complete syntax for exception handling in Python: ... The finally executes even when you return in the try, except, or else and that makes it pretty special.
🌐
Astral
docs.astral.sh › ruff › rules › return-in-try-except-finally
return-in-try-except-finally (SIM107) | Ruff - Astral Docs
def squared(n): try: return_value = n**2 except Exception: return_value = "An exception occurred" finally: return_value = -1 return return_value · Python documentation: Defining Clean-up Actions Back to top
🌐
CodeQL
codeql.github.com › codeql-query-help › python › py-exit-from-finally
‘break’ or ‘return’ statement in finally — CodeQL query help documentation
When a break or return statement is used in a finally block this causes the try-finally block to exit immediately discarding the exception. This is unlikely to be the intention of the developer and makes the code more difficult to read. Either move the break or return statement to immediately ...
🌐
Plain English
plainenglish.io › home › blog › python › caveats of using return with try/except in python
Caveats of using return with try/except in Python
September 3, 2020 - If a finallyclause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception.
🌐
Edureka Community
edureka.co › home › community › categories › python › does finally always execute in python
Does finally always execute in Python | Edureka Community
August 30, 2018 - For any possible try-finally block in Python, is it guaranteed that the finally block will always ... a finally block can fail to execute in Python?
🌐
Codingem
codingem.com › home › python “finally” statement: an ultimate guide (with examples)
Python "finally" Statement: An Ultimate Guide (with Examples)
November 5, 2022 - In Python, the finally statement is helpful with error handling to ensure code executes. For example, here the something_else() call does not run because it is not in an finally block: try: something() except: return None something_else() # This does not get executed