Catch RecursionError and Fail Gracefully in Python
Wrap a recursive function call in a try-except block to catch RecursionError and print a graceful failure message instead of crashing.
Python code
15 linesdef compute_factorial_recursive(n):
"""Compute factorial recursively, raising RecursionError for deep recursion."""
if n == 0:
return 1
return n * compute_factorial_recursive(n - 1)
if __name__ == "__main__":
try:
result = compute_factorial_recursive(10000)
print(f"Factorial computed: {result}")
except RecursionError as e:
print(f"Graceful failure: Recursion limit reached ({e})")
finally:
print("Program finished without crashing.")
Output
Graceful failure: Recursion limit reached (maximum recursion depth exceeded)
Program finished without crashing.
How it works
Python limits recursion depth by default to prevent stack overflow, raising RecursionError when the limit is exceeded. The try-except block catches this specific exception, allowing the program to continue gracefully instead of terminating. The finally block runs regardless, ensuring cleanup or final messages. This pattern is essential for recursive algorithms that may process large inputs.
Common mistakes
- Not catching RecursionError and letting the program crash with an ugly stack trace.
- Using an overly broad `except Exception` which hides other errors.
- Forgetting that deep recursion can also cause memory issues if not handled promptly.
Variations
- Set a custom recursion limit with `sys.setrecursionlimit()` before calling, but be aware of potential crashes.
- Convert the recursion to an iterative loop to avoid the limit entirely.
Real-world use cases
- Parsing deeply nested JSON or XML structures where recursion depth may exceed Python's limit.
- Implementing recursive algorithms like directory traversal where unexpected depth could cause failures.
- Processing recursive data structures in AI pipelines, such as nested prompt templates.
Sponsored
More from Errors & debugging
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
- How to Assert an Invariant After a Complex Transformation in Python easy
Keep learning
Related tutorials and quizzes for this topic.