What is the difference between Error and Exception in Java?

UPDATED: 07 September 2021

Errors and Exceptions are the subclasses of Throwable. However it hold different context for any Java program.
 
Errors result from failures detected by the Java Virtual Machine, such as OutOfMemoryError, StackOverflowError, etc... Most simple programs do not try to handle errors. For errors programs are not expected to recover. Mostly errors results from lack of resources provided to program. An Internal error or resource limitation errors are subclasses of VirtualMachineError.

Source code (StackOverflowErrorExample.java)
/**
 * Example of StackOverflowError in java.
 * @author javaQuery
 * @date 2021-09-07
 * @Github: https://github.com/javaquery/Examples
 */
public class StackOverflowErrorExample {
    private static void recursion(int i){
        if(i == 0){
            System.out.println("Not reachable code");
        }else{
            recursion(i++);
        }
    }

    public static void main(String[] args) {
        recursion(10);
    }
}
  
Exception results when constraints are violated in program. Exception can be checked exception or unchecked exception. For exception programs are expected to recover. Exception can occur at compile time (checked exception: FileNotFoundException) and at run time (unchecked exception: ArithmeticException)

Source code (ArithmeticExceptionExample.java)
/**
 * Example of ArithmeticException in java.
 * @author javaQuery
 * @date 2021-09-07
 * @Github: https://github.com/javaquery/Examples
 */
public class ArithmeticExceptionExample {

    public static void main(String[] args) {
        int x = 10;
        int y = getY();
        System.out.println(x / y);
    }

    /**
     * This is example of getting value from some method call.
     * There is possibilities of getting value `0`.
     *
     * Java compiler can't identify such errors
     */
    public static int getY(){
        return 2-2;
    }
}


0 comments :