-2

I have written a java code which is giving me StackOverflowError:- Here in commented portion I tried catching an exception but wasn't able to handle it.When can we handle StackOverflowError and StackOverflowException?

public class TestExceptions{
public static void main(String [] arg){
try{
  new TestExceptions().go();
}catch(Error r){System.out.println("Error is caught:-"+r);}


/*try{
   new TestExceptions().go();
  }catch(Exception e){System.out.println("Exception is caught here:-"+e);}*/
}
void go(){
    System.out.println("Go method is called:-");
go();
}

}

sumitya
  • 2,631
  • 1
  • 19
  • 32

1 Answers1

3

There is nothing called stackoverflow exception. It is always stackoverflowerror. This link explains why it happens.

What is a StackOverflowError?

Difference between error and exception:

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Refer What is difference between Errors and Exceptions?

You cannot catch an error with exception catch block. Error and Exception both have same parent Throwable. So if you catch the Throwable in the catch block,you will be able to catch stackoverflowerror.

But never catch an error

Community
  • 1
  • 1
Hirak
  • 3,601
  • 1
  • 22
  • 33