C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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();
}
}
Output
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)
...
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");
}
}
Output
Done