When does StackOverflowError occur?

Viewed 4059

According to Oracle, a StackOverflowError is:

Thrown when a stack overflow occurs because an application recurses too deeply.

I know what recursion is and normally recursive functions, if not terminated properly, lead to StackOverflowError. To check the number of recursive calls that happen before StackOverflowError is thrown, I wrote this code:

package ErrorCases;

public class StackOverFlowError {
static int i=0;
void a()
{

    //System.out.println("called "+(++i));
    try{
        ++i;
    a();
    }catch(Error e)
    {
        System.out.println(e.getClass());
        System.out.println(i);
    }
}

public static void main(String[] args) {

       new StackOverFlowError().a();

   }

}

the value of i gives the count of recursive calls to a() before JVM threw StackOverflowError.
The value of i is different in every run like:

output 1: class java.lang.StackOverflowError
           10466
Output 2: class java.lang.StackOverflowError
           10470

My query is ?

  1. How deep the recursion has to happen before JVM throws StackOverflowError?

  2. Can we recover once a StackOverflowError has been thrown?

4 Answers
Related