java.lang.Error in exception handling in java - Program to show StackOverflowError


java.lang.Error
  • Error is a subclass of Throwable
  • Error indicates some serious problems that our application should not try to catch.
  • Errors are abnormal conditions in application.
  • Error and its subclasses are regarded as unchecked exceptions

Must know :
ThreadDeath is an error which application must not try to catch but it is normal condition.



Why application should not try to catch Error?
Because, in most of cases recovery from an Error is almost impossible. So, application must be allowed to terminate.
Example>
Let’s say errors like OutOfMemoryError and StackOverflowError occur and are caught then JVM might not be able to free up memory for rest of application to execute, so it will be better if application don’t catch these errors and is allowed to terminate.


Program to show StackOverflowError >
StackOverflowError is thrown when a stack overflow occurs because an application recurses too deeply.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ExceptionTest {
   public static void main(String[] args) {
          m(); //call recursive method m()
          System.out.println("Code after exception handling");
   }
  
   static void m() {
          try {
                 //method m() calls itself recursively
                 m();
          } catch (StackOverflowError e) {
                 e.printStackTrace();
          }
   }
}
/*OUTPUT
java.lang.StackOverflowError
   at ExceptionTest.m(ExceptionTest.java:18)
   .
   .
   .
   .
   .
   .
   .
   .
Code after exception handling
*/




RELATED LINKS>



EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - detailed explanation with diagrams Set-1 > Q1- Q25


EXCEPTIONS - Top 60 interview questions and answers in java for fresher and experienced - 30 important OUTPUT questions Set-2 > Q26- Q60


No comments:

Post a Comment