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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

15 lines
Python 3.9+
def 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

stdout
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

  1. Set a custom recursion limit with `sys.setrecursionlimit()` before calling, but be aware of potential crashes.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.