try:
recursive_function()
except RuntimeError e:
# is this a max. recursion depth exceeded exception?
How do I tell when the maximum recursion depth has been reached?
Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.
The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.
A Python RecursionError exception is raised when the execution of your program exceeds the recursion limit of the Python interpreter. Two ways to address this exception are increasing the Python recursion limit or refactoring your code using iteration instead of recursion.
You can look inside the exception itself:
>>> def f():
... f()
...
>>> try:
... f()
... except RuntimeError as re:
... print re.args, re.message
...
('maximum recursion depth exceeded',) maximum recursion depth exceeded
I don't think you can distinguish between this and something merely pretending to be a recursion-depth-exceeded (Runtime) exception, though. message
is deprecated, so args
is probably the best bet, and is Python-3 compatible.
Update: in Python 3.5, there's a specific RecursionError
which you can catch instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With