Java : StackOverflowError with Examples

StackOverflowError (Java SE 21 & JDK 21) with Examples.
You will find code examples on most StackOverflowError methods.


Summary

Thrown when a stack overflow occurs because an application recurses too deeply.

Class diagram

class Sample {
    void recursion() {
        System.out.println("Recursion!");
        recursion();
    }
}

final var sample = new Sample();

try {
    sample.recursion();
} catch (StackOverflowError e) {
    System.out.println(e);
}

// Result
// ↓
//Recursion!
//Recursion!
//Recursion!
// ・
// ・
// ・
//java.lang.StackOverflowError

Constructors

StackOverflowError ()

Constructs a StackOverflowError with no detail message.

final var e = new StackOverflowError();
System.out.println(e); // java.lang.StackOverflowError: abcd

StackOverflowError (String s)

Constructs a StackOverflowError with the specified detail message.

final var e = new StackOverflowError("abcd");
System.out.println(e); // java.lang.StackOverflowError: abcd
System.out.println(e.getMessage()); // abcd

Methods declared in Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Please see the link below.


Related posts

To top of page