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.
This program provokes a java.lang.StackOverflowError
. It never terminates. The output is truncated in this example—many more x()
calls are reported.
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) ...
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.
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.