🔧 Error Fixes
· 1 min read

Stack Overflow Error — How to Fix It


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
📘