Home > front end >  Explanation on why Python crashes on some recursion code?
Explanation on why Python crashes on some recursion code?

Time:10-05

The code

def Recursion():
    try:
        raise RecursionError()
    except RecursionError:
        Recursion()

Recursion()

crashes.

I am aware that this is a recursive function, but shouldn't Python just raise an StackError, instead of just crashing? If someone could explain this, I would be very grateful!

CodePudding user response:

Something similar has been reported as a bug: https://bugs.python.org/issue42509, with someone commenting that

Catching a RecursionError might be fine sometimes, but the issue is that Program 1 catches a RecursionError and then keeps recursing more rather than stopping.

I think it might have to be the responsibility of the Python user to make sure that if a RecursionError is to be caught, that the program can recover without making things much worse. It's my understanding that the extra buffer of 50 is to make sure that the programmer has room to stop the overflow and do any necessary cleanup [1].

If no attempt is made to clean up, then it seems reasonable to me that Python should crash, unless there's some idea of what could happen that I'm missing. The interpreter could allow arbitrary recursion during the cleanup until the C stack overflows, but that sort of defeats the point of the recursion checker. It could raise some new ExtraSuperRecurionError, but that doesn't fix anything: what if that error is caught ;) ?

https://bugs.python.org/msg382128

Assuming this is a minimally reproducible toy example for a real issue you're facing, you should do:

def Recursion():
    try:
        raise Exception()
    except RecursionError:
        raise
    except Exception:
        Recursion()

Recursion()

CodePudding user response:

The RecursionError that you see is not the one you manually raise. It does not occur within the try-block and therefore is not caught:

def Recursion():
    try:
        raise RecursionError()  # does not happen here ...
    except RecursionError:
        Recursion()  # ... but here where it goes unhandled
  • Related