Error vs Exception

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Both subclass Throwable.
  • Exception: Represents conditions that a reasonable application might want to catch and recover from (e.g., FileNotFoundException).
  • Error: Represents serious, catastrophic problems with the JVM or environment that an application should not try to catch (e.g., OutOfMemoryError).

Concept

java.lang.Exception

Exceptions are meant to be handled. If your program asks a user for an age and they type “Twenty”, a NumberFormatException is thrown. Your program can easily catch this, print “Please enter a number”, and let the user try again.

java.lang.Error

Errors indicate that something went fundamentally wrong at the system level.

  • OutOfMemoryError: The JVM has run out of RAM.
  • StackOverflowError: A recursive function recursed too deeply and blew up the stack memory.
    If an Error occurs, the application is in an unstable state. There is almost no reasonable way to recover from running out of RAM programmatically; the JVM will shut down.

Examples

public class ErrorVsException {

    // 1. Triggering an Exception (Recoverable)
    public static void causeException() {
        try {
            int[] arr = new int[5];
            arr[10] = 50; // Throws ArrayIndexOutOfBoundsException
        } catch (Exception e) {
            System.out.println("Caught an exception! Program continues.");
        }
    }

    // 2. Triggering an Error (Unrecoverable)
    public static void causeError() {
        // Infinite recursion
        // Throws java.lang.StackOverflowError
        causeError(); 
    }

    public static void main(String[] args) {
        causeException();
        
        System.out.println("About to cause an Error...");
        // causeError(); // This will crash the JVM!
    }
}

Interview Questions

Q: Is an Error checked or unchecked?
A: Technically, all Errors are unchecked. The compiler does not force you to declare throws OutOfMemoryError on your methods, nor does it force you to wrap your code in a try-catch block.

Q: Can you catch an Error using a try-catch block?
A: Yes, you can syntactically write catch (OutOfMemoryError e) or catch (Error e), and the compiler will allow it. However, you absolutely should not do this. When an Error occurs, the JVM’s state is compromised, and trying to continue execution is dangerous and unpredictable.