4

Earlier today I read about this strange case in Python, Java & JS:

try:
    return True
finally:
    return False

Which returns False.

So, I decided to toy around with it:

def caseThree():
    try:
        caseThree()
    except:
        print("Error")
        caseThree()
    finally:
        return False
print(caseThree())

In Python 2.7 this returns:

Error
False

However, in Python 3.5:

Error
Fatal Python error: Cannot recover from stack overflow.

Current thread 0x000025ec (most recent call first):
  File "`<stdin>`", line 3 in caseThree

the last line is repeated until you eventually get: ...

Can anyone explain why 2.7's code doesn't result in a stack overflow, while 3.5 does?

5
  • 2
    "the only difference is that we moved the recursion from the finally to the try" - why did you expect that this wouldn't change the output? It's not clear what is surprising you here, or why. Could you focus on one specific problem? Commented Nov 27, 2016 at 12:41
  • 1. RecursionError (RuntimeError before Python 3.5) is just an exception and may be caught and handled by try/except/finally constructs. 2. finally block have to be executed. These two statements is all you need to interpret what's happening in your code. Commented Nov 27, 2016 at 12:45
  • Edited the question to focus on one problem, as suggested by @jonrsharpe Commented Nov 27, 2016 at 12:48
  • Could you fix the title? We're not aspiring to click bait here! Commented Nov 27, 2016 at 12:49
  • 1
    Not exactly sure why 2 people have voted to close as "unclear what you're asking". It's pretty clear what is being asked. Commented Nov 27, 2016 at 13:29

1 Answer 1

2

It seems that the error you're encountering is actually expected, as it is explicitly tested for in Lib/test/test_sys.py function test_recursionlimit_fatalerror.

Now, without criticizing your colorful experiments, this is also the cause of a bug that causes a segfault (sometimes, see issue); there has already been one report of this to the Python bug tracker as issue 28179.

Keep an eye on that thread if you're curious as to what is causing this.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.