Showing results for python try except return
Search instead for python tryexcept return

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

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
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
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
0
0
December 20, 2023
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
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 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.
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.

🌐
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 › 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)
🌐
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
🌐
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)
🌐
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.
🌐
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
🌐
Matt Might
matt.might.net › articles › implementing-exceptions
You don't understand exceptions, but you should
The variable $current-handler holds a pointer to the current exception handler. An isolated desugaring of the try form is not hard: (let ([$old (current-handler)]) (call/ec (lambda (ec) (set-current-handler! (lambda (ex) (set-current-handler! $old) (ec (handler ex)))) (let ([rv body]) (set-current-handler! $old) rv)))) ... Whether the body returns naturally, or by invoking an exception, the old handler gets restored.
🌐
Python.org
discuss.python.org › python help
Run code finally before returning in except - Python Help - Discussions on Python.org
December 6, 2023 - try: # Some Code.... except: # Handling of exception return False else: # execute if no exception finally: print('done') # Execute before returning False incase of an exce…
🌐
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 › 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   September 8, 2024
🌐
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)
Top answer
1 of 3
5

Neither of these is more Pythonic than the other. The examples are too trivial to say which is preferrable but it really all depends on how things should work.

Catch and logging/reporting an issue is just a hair's breadth away from squashing exceptions which is almost always a terrible idea. The only reason I can see doing this is that you want whatever the issue is to not stop execution. If you are going to do something like this, it's really crucial to make sure that you return something sensible that works for the caller. If the next thing that happens is that the calling code throws its own exception because e.g., None doesn't have an add method, you are at best just making things harder to troubleshoot. It could be a lot worse, however. A lot of serious bugs are due to returning nulls/None after catching an error. I think there are times that is makes sense to do this, but they are rare in my experience.

Allowing the raw exception to bubble out is the next least-worst option, IMO. This can be fine if you are building something small where it will be easy to find the what the problem is when things crash with a KeyError. In a situation where you are leveraging a lot of duck-typing, passing around function references, or using annotations, it can sometimes be difficult. For example, if you are using this code behind a web endpoint, what HTTP error code should you use when you catch a KeyError. 500 might be the right answer in most cases but there might be times you want to produce something else depending on where the key was not found.

That brings me to the last option which you don't mention: catch and raise a separate, more meaningful error. That allows you to distinguish between say, a KeyError thrown because the request was for something that isn't valid and a KeyError thrown because of a bad configuration.

2 of 3
4

Neither is pythonic. Pythonic code would be:

my_dict = {}
def fetch_value(key):
    return my_dict[key]

val = fetch_value('my_key')

Remember, simple is better than complex and flat is better than nested. Since your except-block does not handle the exception in any meaningful way, it is better to just let it bubble up the call stack and terminate the program.

But in your code the error is ignored and it implicitly returns None if the key is not found. If this is what you want, then it can be done simpler with the get() method:

def fetch_value(key):
    return my_dict.get(key)

"Handling" an error by just logging a message and then continuing as if nothing happened, is a terrible antipattern from the Java world which has no place in Python. Exceptions should only be caught if they can be meaningfully handled.

🌐
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'
🌐
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 - Even if there’s an error in an exception handler or the else-block and a new exception is raised, the code in the final-block is still run. This quote from the python documentation is absolutely correct but the execution behavior is little tricky when try and finally blocks are encapsulated within a function which has a return statement.
🌐
freeCodeCamp
freecodecamp.org › news › python-try-and-except-statements-how-to-handle-exceptions-in-python
Python Try and Except Statements – How to Handle Exceptions in Python
September 23, 2021 - In most cases, you can use only the try block to try doing something, and catch errors as exceptions inside the except block. Over the next few minutes, you'll use what you've learned thus far to handle exceptions in Python. Let's get started. Consider the function divide() shown below. It takes two arguments – num and div – and returns ...
🌐
TechBeamers
techbeamers.com › use-try-except-python
Try-Except in Python: The Beginner’s Guide - TechBeamers
November 30, 2025 - An error is caught by the try-except clause. After the code in the except block gets executed, the instructions in the [finally clause] will run. Please note that a [finally block] will ALWAYS run, even if you’ve returned ahead of it.