Exceptions: StackOverflowError is a Throwable you can catch like any exception

StackOverflowError is an Error, not an Exception, but both extend Throwable, so a catch block can still handle it and let the program recover instead of crashing, which this snippet demonstrates with unbounded recursion.

Code
static int recurse(int depth) {
    return 1 + recurse(depth + 1);
}
try {
    recurse(0);
} catch (StackOverflowError e) {
    System.out.println("Caught: " + e.getClass().getSimpleName());
}
System.out.println("Program continues after the overflow");
Output
Caught: StackOverflowError
Program continues after the overflow
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms