Home
Map
StackOverflowErrorAnalyze the StackOverflowError and see a solution for recursive methods.
Java
This page was last reviewed on May 26, 2023.
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
C#VB.NETPythonGolangJavaSwiftRust
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
Home
Changes
© 2007-2023 Sam Allen.