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.
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");
Caught: StackOverflowError
Program continues after the overflow
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