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
🌐
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") ...
Discussions

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 function with try, except, finally, and return
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 statement that called the function. Literature on Python also offers much ... More on discuss.codecademy.com
🌐 discuss.codecademy.com
0
9
August 23, 2020
python - Weird Try-Except-Else-Finally behavior with Return statements - Stack Overflow
It is worth mentioning that PEP765 ... in Python 3.14. This construct now emits a SyntaxWarning. 2025-10-07T16:00:47.493Z+00:00 ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... ... 0 Why is a `return` statement inside of except block silently not executed if finally block contains a return statement? 1 Nested try-except-finally ... More on stackoverflow.com
🌐 stackoverflow.com
Is it okay to use try/finally without except?
Code after finally will be called whether the code after the try works or not. It doesn't care. Gets called every time. If you need something to run IF AND ONLY IF the code in the try FAILS, then you need to use except. More on reddit.com
🌐 r/learnpython
6
11
February 12, 2016
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
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
🌐
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: ...
🌐
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
Find elsewhere
🌐
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 - To have a clearer idea of the execution ... try: x = 10 print(f" Inside try block ") return x except Exception as e: x = 20 print(f" Inside except block ") return x finally: x = 30 print(f" Inside finally block ") return x print(test_func()) Output: Inside ...
🌐
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 statement that called the function. Literature on Python also offers much information on handling exceptions.
🌐
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
🌐
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 Tutorial
pythontutorial.net › home › python basics › python try…except…finally
Python try...except...finally Statement - Python Tutorial
March 30, 2025 - Therefore, all statements in the try and finally clauses execute: a = 10 b = 2 try: c = a / b print(c) except ZeroDivisionError as error: print(error) finally: print('Finishing up.') Code language: PHP (php)
🌐
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
Even if you return from the except, the finally code is run. If you also return from the finally, that value is what’s returned. It’s handy for freeing up resources that may not be released when Python garbage-collects things. It’s not used all that much in my work, about as much as the “else” after a for loop (yeah, look *that* one up!). ... Finally always gets called when you complete a try/except.
🌐
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()
🌐
Real Python
realpython.com › lessons › python-return-try-finally
Using return With try and finally Blocks (Video) – Real Python
If it is unsuccessful, then a ValueError will occur, and the return statement in the except clause will be executed, which returns the argument in values as a string. 02:13 In either case, since this try statement has a finally clause, it will be executed before the function returns.
Published   August 10, 2021
🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
January 29, 2026 - The finally block is executed regardless of whether an exception occurs or not. Finally blocks are useful, for example, when you want to close a file or a network connection regardless of what happens. After all, you want to clean up resources to prevent memory leaks. Here’s an example of this at work, in which we open a file without using the with statement, forcing us to close it ourselves: try: # Open file in write-mode f = open("myfile.txt", 'w') f.write("Hello World!") except IOError as e: print("An error occurred:", e) finally: print("Closing the file now") f.close()Code language: Python (python)
🌐
Python for Network Engineers
pyneng.readthedocs.io › en › latest › book › 06_control_structures › exceptions.html
Working with try/except/else/finally - Python for network engineers
$ python divide_ver2.py Enter first number: 5 Enter second number: 0 Something went wrong... ... In block except you don’t have to specify a specific exception or exceptions. In that case, all exceptions would be intercepted. That is not recommended! Try/except has an optional else block. It is implemented if there is no exception. For example, if you need to perform any further operations with data that user entered, you can write them in else block (divide_ver3.py file):
🌐
Python
docs.python.org › 2.5 › whatsnew › pep-341.html
6 PEP 341: Unified try/except/finally
July 31, 2012 - Guido van Rossum spent some time working with Java, which does support the equivalent of combining except blocks and a finally block, and this clarified what the statement should mean. In Python 2.5, you can now write: try: block-1 ... except Exception1: handler-1 ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - Example: Python · # Program to depict else clause with try-except # Function which returns a/b def AbyB(a , b): try: c = ((a+b) // (a-b)) except ZeroDivisionError: print ("a/b result in 0") else: print (c) # Driver program to test above function ...