您在這裡

Infinite recursion

1 九月, 2015 - 16:57

If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as innite recursion, and it is generally not a good idea. Here is a minimal program with an infinite recursion:

def recurse():
    recurse()

In most programming environments, a program with infinite recursion does not really run forever. Python reports an error message when the maximum recursion depth is reached:

    File "<stdin>", line 2, in recurse
    File "<stdin>", line 2, in recurse
    File "<stdin>", line 2, in recurse
                    .
                    .
                    .
    File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded

This traceback is a little bigger than the one we saw in the previous chapter. When the error occurs, there are 1000 recurse frames on the stack!