return eats exception

exception, finally, python, return

Solution

You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return).

Problem

I found the following behavior at least weird: ``` def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined ``` The exception disappears when you use `return` inside a `finally` clause. Is that a bug? Is that documented anywhere? But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?

Original source