Difference Between Error and Exception in Java. Error vs Exception

However, both Errors and Exceptions are the subclasses of java.lang.Throwable class but an Error indicates serious problems that a reasonable application should not try to catch, while we can catch exceptions at runtime using try, catch and finally blocks.

An error can never be recovered whereas, an exception can be recovered by preparing the code to handle the exception.

Following are the major differences between Error and Exception.

Error Exception
An error is caused due to lack of system resources. An exception is caused because of the code.
An error is irrecoverable. An exception is recoverable.
There is no means to handle an error by the program code. Exceptions are handled using 3 keywords try, catch, and throw.
As and when an error is detected, program will be terminated abnormally. As aand when an exception is detected, it is thrown and caught by throw and catch keywords.
Errors are classified as unchecked type. Exceptions are classified as checked or unchecked type.
Errors are defined in java.lang.Error package. Exceptions are defined in java.lang.Exception.
Some examples of errors are -
OutOfMemory, StackOverFlow.
Some examples of exceptions are -
Checked Exceptions : NoSuchMethod, ClassNotFound.
Unchecked Exceptions : NullPointer, IndexOutOfBounds.

Error Example

class StackOverflow { 
    public static void test(int i) 
    { 
        // No correct as base condition leads to 
        // non-stop recursion. 
        if (i == 0) 
            return; 
        else { 
            test(i++); 
        } 
    } 
} 
public class ErrorEg { 
 
    public static void main(String[] args) 
    { 
 
        // eg of StackOverflowError 
        StackOverflow.test(5); 
    } 
} 
 
OUTPUT
======
Exception in thread "main" java.lang.StackOverflowError
    at StackOverflow.test(ErrorEg.java:7)
    at StackOverflow.test(ErrorEg.java:7)
    at StackOverflow.test(ErrorEg.java:7)
    at StackOverflow.test(ErrorEg.java:7)
    at StackOverflow.test(ErrorEg.java:7)

Exception Example

public class ExceptionEg { 
    public static void main(String[] args) 
    { 
        int a = 5, b = 0; 
        // Attempting to divide by zero 
        try { 
            int c = a / b; 
        } 
        catch (ArithmeticException e) { 
            e.printStackTrace(); 
        } 
    } 
} 
 
OUTPUT
======
java.lang.ArithmeticException: / by zero
    at ExceptionEg.main(ExceptionEg.java:8)

Hope you have enjoyed reading Difference Between Error and Exception in Java. Error vs Exception Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.