StackOverflowError

java.lang.StackOverflowError

Quick Answer

Your code has infinite or excessively deep recursion. Add a base case to your recursive method or convert to iteration.

Why This Happens

Each method call adds a frame to the call stack. When recursion has no proper base case or the recursion depth is too large, the stack runs out of space. This also happens with circular method calls like A calls B calls A, or accidentally recursive toString() or equals() methods.

The Problem

public int factorial(int n) {
    return n * factorial(n - 1); // No base case!
}

The Fix

public int factorial(int n) {
    if (n <= 1) return 1; // Base case
    return n * factorial(n - 1);
}

Step-by-Step Fix

  1. 1

    Identify the recursive call

    Look at the stack trace for repeated method names. The repeating pattern shows which methods form the recursive cycle.

  2. 2

    Find the missing base case

    Check the recursive method for a termination condition. If it exists, verify it is reachable for all inputs.

  3. 3

    Add base case or convert to iteration

    Add a proper base case that stops recursion, or rewrite the method using a loop and explicit stack if recursion depth could be large.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free