Java Programs

Difference between Exception and Error

In Java, both exceptions and errors are subclasses of the Throwable class. The error indicates a problem that occurs mainly due to lack of system resources, and our application should not catch this type of problem. Some of the examples of errors are system crash errors and memory insufficient errors. Errors mostly occur at runtime, which means that they belong to an unchecked type.

Exceptions are problems that can occur at runtime and at compile time. They mainly occur in the code written by developers. Exceptions are divided into two categories: checked exceptions and unchecked exceptions.

Difference between Error and Exception

Sr. No.KeyErrorException
1Type Classified as an unchecked type Classified as checked and unchecked 
2Package It belongs to java.lang.error It belongs to java.lang.Exception 
3Recoverable/ IrrecoverableIt is irrecoverableIt is recoverable
 When This OccurIt can’t be occur at compile time It can occur at run time and compile time both 
5ExampleOutOfMemoryError ,IOError NullPointerException , SqlException 

Exception Example

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)

Error Example

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)

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs