Home
Search
Java StackOverflowErrorAnalyze the StackOverflowError and see a solution for recursive methods.
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.
Java program that causes StackOverflowError
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).
Java program that checks recursion depth
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.
Exceptions
Home
© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.