Home
Java
StackOverflowError
Updated May 26, 2023
Dot Net Perls
StackOverflowError. As a method is called, it occupies a frame on the stack—an activation record. In a recursive method, many methods can be called, deeper and deeper.
At some depth, this causes an error—a StackOverflowError. The program will terminate. And we will be left with a confusing message.
An example. This program provokes a java.lang.StackOverflowError. It never terminates. The output is truncated in this example—many more x() calls are reported.
Note This program is hopeless in its current form. With a count argument, though, we can prevent excess recursion.
public class Program { public static void x() { // This recurses infinitely. x(); } public static void main(String[] args) { // Call the x method the first time. x(); } }
Exception in thread "main" java.lang.StackOverflowError at Program.x(Program.java:5) at Program.x(Program.java:5) at Program.x(Program.java:5) at Program.x(Program.java:5) ...
Check depth. Here we introduce a count argument (an int) to our x() method. We add one to count on each nested call to "x." This restricts the depth of recursion.
Tip This program will only ever have a recursion depth of 11 (it starts at 0 and continues until 10).
public class Program { public static void x(int count) { // Check the count argument to prevent StackOverflowError. if (count >= 10) { return; } x(count + 1); } public static void main(String[] args) { // Begin. x(0); System.out.println("Done"); } }
Done
With StackOverflowError, we have a descriptive error. Our program has a stack depth that is too great. We can restrict stack depth in certain recursive methods with an argument.
try
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
No updates found for this page.
Home
Changes
© 2007-2025 Sam Allen