StackOverflowError in a runtime error in java. It is thrown when an application recurses too deeply. Whenever the method execution happens a call stack with limited amount of memory location is assigned. This amount of memory is allocated by JVM. Based upon the number of the method execution the size of the call stack grows and srinks.
In most of the cases StackOverFlowError is thrown when call stack exceeds because of excessive deep or infinite recursion. During which the need to store the local variable in the method exceeds the allocated stack size.
A StackOverflowError simply signals that there is no more memory available.
public class Main { int calculateFactorial(int number) { return number * calculateFactorial(number - 1); } public static void main(String[] args) { Main main = new Main(); System.out.println(main.calculateFactorial(10)); } } |
Output
Exception in thread "main" java.lang.StackOverflowError at Main.calculateFactorial(Main.java:3) at Main.calculateFactorial(Main.java:3) |
How to deal with StackOverflowError
Analyse the code and exception stack trace. Then do the following based on your analysis
- Remove recursion with no termination condition from application.
- Remove cyclic dependency between classes.
- Remove instance if exist like class instance within the same class as an instance variable of that specified class.
- Increase stack size, if none of the conditions are there in the application.
Java interview questions on Exception Handling
- what is an exception?
- How the exceptions are handled in java?
- What is the difference between error and exception in java?
- Can we keep other statements in between try catch and finally blocks?
- Explain the exception hierarchy in java?
- What are runtime exceptions in java?
- What is outofmemoryerror in java?
- What are checked and unchecked exceptions in java?
- What is the difference between classnotfoundexception and noclassdeffounderror in java?
- Will finally block get executed if return?
- Can we throw an exception without throws?
- What is rethrowing an exception in java?
- What is the use of throws keyword in java?
- What is exception propagation in java?
- Difference between throw and throws in java?
- What is finally in java?
- What is the difference between final finally and finalize in java?
- How to create customized exceptions in java?
- What is classcastexception in java?
- What is stackoverflowerror in java?
- What is the superclass of all exception classes?
- What is the use of printstacktrace method in java?
- What is arraystoreexception in java?