java.lang.StackOverflowError
SystemStackError: stack level too deep
RecursionError: maximum recursion depth exceeded
A function is calling itself (or calling another function that calls it back) until the call stack runs out of space.
Fix 1: Add a Base Case
# β No base case β infinite recursion
def factorial(n):
return n * factorial(n - 1)
# β
Add a stopping condition
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
Fix 2: Fix Accidental Recursion
// β toString() calls itself
@Override
public String toString() {
return "User: " + this; // π₯ Calls toString() again
}
// β
Reference specific fields
@Override
public String toString() {
return "User: " + this.name;
}
Fix 3: Convert to Iteration
// β Deep recursion for large inputs
function sum(n) {
if (n <= 0) return 0;
return n + sum(n - 1); // π₯ Fails for n > ~10000
}
// β
Iterative version
function sum(n) {
let total = 0;
for (let i = 1; i <= n; i++) total += i;
return total;
}
Fix 4: Increase Stack Size (Temporary)
# Java
java -Xss4m MyApp
# Python
import sys
sys.setrecursionlimit(10000)
# Node.js
node --stack-size=8192 app.js
This is a band-aid β fix the recursion instead.
Fix 5: Circular Object References
// β A references B, B references A
class Parent {
Child child;
}
class Child {
Parent parent; // Serializing this β StackOverflow
}
// β
Break the cycle in serialization
// Use @JsonIgnore, transient, or a DTO
Debugging
# Python: find the recursive call
import traceback
try:
my_function()
except RecursionError:
traceback.print_exc() # Shows the repeating call