Difference between Exception and Error in Java

JavaObject Oriented ProgrammingProgramming

Exceptions and errors both are subclasses of Throwable class. The error indicates a problem that mainly occurs due to the lack of system resources and our application should not catch these types of problems. Some of the examples of errors are system crash error and out of memory error. Errors mostly occur at runtime that's they belong to an unchecked type. 

Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the developers.  Exceptions are divided into two categories such as checked exceptions and unchecked exceptions. 

Sr. No.KeyErrorException
1
Type 
Classified as an unchecked type 
Classified as checked and unchecked 
2
Package 
It belongs to java.lang.error 
It belongs to java.lang.Exception 
3
Recoverable/ Irrecoverable
It is irrecoverable
It is recoverable

 It can't be occur at compile time 
It can occur at run time compile time both 
5
Example
OutOfMemoryError ,IOError 
NullPointerException , SqlException 

Example of Error

public class ErrorExample {
   public static void main(String[] args){
      recursiveMethod(10)
   }
   public static void recursiveMethod(int i){
      while(i!=0){
         i=i+1;
         recursiveMethod(i);
      }
   }
}

Output

Exception in thread "main" java.lang.StackOverflowError
   at ErrorExample.ErrorExample(Main.java:42)

Example of Exception

public class ExceptionExample {
   public static void main(String[] args){
      int x = 100;
      int y = 0;
      int z = x / y;
   }
}

Output

java.lang.ArithmeticException: / by zero
   at ExceptionExample.main(ExceptionExample.java:7)
raja
Published on 18-Nov-2019 06:54:35
Advertisements