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

Discussions

python - Why finally-block is executed after a try-block containing return statement - Stack Overflow
I'm wondering why the function foo is returning 3 instead 1. Please explain. def foo(): try: return 1 except: return 2 finally: return 3 More on stackoverflow.com
🌐 stackoverflow.com
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
python - Weird Try-Except-Else-Finally behavior with Return statements - Stack Overflow
Because when the return statement is called, Python checks for any open finally clauses that need to be executed (see the quote above). 2012-06-22T21:28:13.43Z+00:00 ... try block make a return value and call return -> finally block -> popup return value -> function ends More on stackoverflow.com
🌐 stackoverflow.com
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute · Example: Let's try to throw the exception in except block and Finally will execute either exception will generate or not...
Published   July 15, 2025
🌐
Astral
docs.astral.sh › ruff › rules › return-in-try-except-finally
return-in-try-except-finally (SIM107) | Ruff - Astral Docs
This can lead to unexpected behavior. def squared(n): try: sqr = n**2 return sqr except Exception: return "An exception occurred" finally: return -1 # Always returns -1. ... def squared(n): try: return_value = n**2 except Exception: return_value = "An exception occurred" finally: return_value ...
🌐
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 - Function example_1 is simple and straight, first the try-block gets executed and then final-block. The variable val has value 1 in try-block and gets updated to 2 in final-block. # The try block has return statement & final block has only print ...
🌐
Real Python
realpython.com › lessons › python-return-try-finally
Using return With try and finally Blocks (Video) – Real Python
Specifically, this means that the finally clause will always be executed when the try statement is encountered. 00:52 So even though the finally clause may appear after one or more return statements, it should not be viewed as dead code. Here is an example of a try statement.
Published   August 10, 2021
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
You can use the else keyword to define a block of code to be executed if no errors were raised: In this example, the try block does not generate any error: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") ...
Find elsewhere
🌐
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
It's generally put after the catch block. It only have some default statements to be executed. ... Write better C++ code with less effort. Boost your efficiency with refactorings, code analysis, unit test support, and an integrated debugger. ... 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.
🌐
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()
🌐
Python
peps.python.org › pep-0765
PEP 765 – Disallow return/break/continue that exit a finally block | peps.python.org
November 15, 2024 - However, even if the except Exception was changed to except BaseException, this code would still have the problem that the finally block swallows all exceptions raised from within the except block, and this is probably not the intention (if it is, that can be made explicit with another try-except BaseException). Another variation on the issue found in real code looks like this: try: ... except: return NotImplemented finally: return some_value
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: >>> try: ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') ... Goodbye, world!
🌐
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 ...
🌐
Justin Joyce
justinjoyce.dev › home › latest › python try except
Python try except | Justin Joyce
February 18, 2024 - All non-fatal Python exception classes inherit from Exception, so you’ll catch almost any exception this way. me = {"name": "justin", "age": 100} def get_age(person): try: print("Getting age") return person["age"] except KeyError as e: print("key error hit") finally: print("finally block hit") my_age = get_age(me) # Getting age # finally block hit print(my_age) # 100
🌐
Tutorialspoint
tutorialspoint.com › python › python_tryfinally_block.htm
Python - The try-finally Block
Following is an example for a single exception − · # Define a function here. def temp_convert(var): try: return int(var) except ValueError as Argument: print("The argument does not contain numbers\n",Argument) # Call above function here.
🌐
Python
peps.python.org › pep-0601
PEP 601 – Forbid return/break/continue breaking out of finally | peps.python.org
August 26, 2019 - This will return cleanly (without an exception) even though it has infinite recursion and raises an exception within the try. The reason is that the return within the finally will silently cancel any exception that propagates through the finally suite. Such behaviour is unexpected and not at all obvious. This function is equivalent to: ... break and continue have similar behaviour (they silence exceptions) if they jump to code outside the finally suite. For example:
🌐
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 finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement · An else clause will get executed if the try block does not raise an exception
🌐
Codecademy Forums
discuss.codecademy.com › community › town square
Python function with try, except, finally, and return - Town Square - Codecademy Forums
August 23, 2020 - As we have observed in instructional content, technical literature, and official Python documentation, a return statement, when executed, terminates execution of the function that contains it, and delivers a value to the…