http://docs.python.org/reference/compound_stmts.html#the-try-statement

The optional else clause is executed if and when control flows off the end of the try clause.

Currently, control “flows off the end” except in the case of an exception or the execution of a return, continue, or break statement.

Answer from wRAR on Stack Overflow
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong") Try it Yourself » · See more Error types in our Python Built-in Exceptions Reference.
Discussions

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?
It doesn't ignore anything, It's just that the finally block is guaranteed to always be called, so it's triggered at the point the return statement is reached. The docs cover this explicitly: 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.’ More on reddit.com
🌐 r/learnpython
9
9
May 30, 2023
python - Is it correct to use a return statement within a try and except statement? - Stack Overflow
If I have such code in the end of function: try: return map(float, result) except ValueError, e: print "error", e Is it correct to use try / except in return part of method? Is there a wis... More on stackoverflow.com
🌐 stackoverflow.com
Allow `break` and `return` inside `except*` clause - Ideas - Discussions on Python.org
PEP 654 (Exception Groups) forbids usage of break, return and continue inside the new except* block. The reason for this given in the PEP is that exceptions in an ExceptionGroup are assumed to be independent, and the presence or absence of one of them should not impact handling of the others ... More on discuss.python.org
🌐 discuss.python.org
1
December 12, 2022
Functions Try Except
Hi. I am a bit confused on why the below code will produce a result of 3? Thank you. m = 0 def foo(n): global m assert m==0 try: return 1/n except ArithmeticError: m+=1 raise try: foo(0) except ArithmeticError: m+=2 except: m+=1 print(m) More on discuss.python.org
🌐 discuss.python.org
4
0
December 20, 2023
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.4 documentation
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
July 23, 2025 - In Python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception. ... # 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 AbyB(2.0, 3.0) AbyB(3.0, 3.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.

Top answer
1 of 3
13

Keep it simple: no try block

It took me a while to learn, that in Python it is natural, that functions throw exceptions up. I have spent too much effort on handling these problems in the place the problem occurred.

The code can become much simpler and also easier to maintain if you simply let the exception bubble up. This allows for detecting problems on the level, where it is appropriate.

One option is:

try:
    return map(float, result)
except ValueError, e:
    print "error", e
    raise

but this introduces print from within some deep function. The same can be provided by raise which let upper level code to do what is appropriate.

With this context, my preferred solution looks:

return map(float, result)

No need to dance around, do, what is expected to be done, and throw an exception up, if there is a problem.

2 of 3
2

If you surround the code block containing a return statement with an try/except clause, you should definitely spend some thoughts of what should be returned, if an exception actually occurs:

In you example, the function will simply return None. If it's that what you want, I would suggest to explicitely add a return None like

except ValueError, e:
    print "error", e
    return None

in your except block to make that fact clear.

Other possibilities would be to return a "default value" (empty map in this case) or to "reraise" the exception using

except ValueError, e:
    print "error", e
    raise

It depends on how the function is used, under what circumstances you expect exceptions and on your general design which option you want to choose.

🌐
Python.org
discuss.python.org › ideas
Allow `break` and `return` inside `except*` clause - Ideas - Discussions on Python.org
December 12, 2022 - PEP 654 (Exception Groups) forbids usage of break, return and continue inside the new except* block. The reason for this given in the PEP is that exceptions in an ExceptionGroup are assumed to be independent, and the presence or absence of one of them should not impact handling of the others I think the first assumption i.e. that exceptions are independent is sensible.
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › python-print-exception-how-to-try-except-print-an-error
Python Print Exception – How to Try-Except-Print an Error
March 15, 2023 - In this article, you’ll learn how to use that try…except syntax to handle exceptions in your code so they don’t stop your program from running. ... In Python, an exception is an error object.
🌐
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
🌐
Rollbar
rollbar.com › home › what is “except exception as e” in python?
What is “except Exception as e” in Python? | Rollbar
June 24, 2024 - The Exception part specifies that any exception of this type or its subclasses should be caught, and the as e part assigns the caught exception to a variable e, which you can then use to access details about the exception. ... try: # Code that might raise an exception result = 10 / 0 # Raises ZeroDivisionError except Exception as e: # Handles the exception print(f"An error occurred: {e}")
🌐
Python.org
discuss.python.org › python help
Functions Try Except - Python Help - Discussions on Python.org
December 20, 2023 - Hi. I am a bit confused on why the below code will produce a result of 3? Thank you. m = 0 def foo(n): global m assert m==0 try: return 1/n except ArithmeticError: m+=1 raise try: foo(0) except ArithmeticError: m+=2 except: m+=1 print(m)
🌐
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 - Let’s carefully take one step at a time to understand the usage of return statements during exception handling. def test_func(): try: x = 10 return x except Exception as e: x = 20 return x finally: x = 30 return x print(test_func()) Output: 30
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
The code enters the else block only if the try clause does not raise an exception. Example: Else block will execute only when no exception occurs. ... # Python code to illustrate working of try() def divide(x, y): try: # Floor Division : Gives only Fractional # Part as Answer result = x // y except ZeroDivisionError: print("Sorry !
Published   July 15, 2025
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
🌐
Zero To Mastery
zerotomastery.io › blog › python-try-except
Beginners Guide To Try-Except In Python | Zero To Mastery
November 22, 2024 - With try-except, you don’t have to worry about your script breaking when things go wrong. Instead of testing everything in advance, you let the program handle issues as they happen. It’s like saying, “Let’s give this code a shot, and if it fails, I’ll handle it.” Your program stays in control and keeps running smoothly. ... Imagine dividing numbers, but by mistake, you divide by zero. Normally, Python would throw a ZeroDivisionError and stop everything.
🌐
Towards Data Science
towardsdatascience.com › home › latest › do not abuse try except in python
Do Not Abuse Try Except In Python | Towards Data Science
January 19, 2025 - The error message we can get from the exception object e is sometimes very limited. I would say that it does not always make sense in Python. In fact, the previous one is not too bad because at least it tells you why the error happened. Let’s see this one. def f4(key): try: d = {'a': 1, 'b': 2} return d[key] except Exception as e: print('Error: ', e)
🌐
Justin Joyce
justinjoyce.dev › home › latest › python try except
Python try except | Justin Joyce
February 18, 2024 - Try and except are the building blocks of exception handling in Python. You’ll also sometimes see finally and else. Here’s the summary: ... You’ll usually see try and except by themselves; finally is used less often, and else even less. Here’s a (slightly) more realistic example: me = {"name": "justin"} def get_age(person): try: return person["age"] except KeyError as e: print(f"caught key error: {e}") # There's no 'age' key on the dict get_age(me) # caught key error: 'age'
🌐
Career Karma
careerkarma.com › blog › python › python try except: a step-by-step guide
Python Try Except: A Step-By-Step Guide | Career Karma
December 1, 2023 - When syntax errors occur, they return the file name, line number, and an indicator of where an error may be present. Exceptions are a type of error where code may have the right syntax but still contains a problem.