Error vs Exception in Java – Key Differences Explained
In Java, everything that can be thrown is a Throwable, and Throwable has two branches: Error and Exception. They look similar in code, but they mean very different things. An Exception is a problem your program can expect and often recover from. An Error is a serious problem in the JVM or its environment that your program usually cannot fix.
This tutorial explains the difference with examples, lists the most common errors, and shows what you should and should not catch.
1. Where They Sit in the Hierarchy
public class ErrorVsException {
static void describe(Throwable t) {
String kind = (t instanceof Error) ? "Error" : (t instanceof RuntimeException) ? "unchecked Exception" : "checked Exception";
System.out.printf("%-32s -> %s%n", t.getClass().getSimpleName(), kind);
}
public static void main(String[] args) {
describe(new OutOfMemoryError());
describe(new StackOverflowError());
describe(new NoClassDefFoundError());
describe(new java.io.IOException());
describe(new InterruptedException());
describe(new NullPointerException());
describe(new IllegalArgumentException());
}
}
OutOfMemoryError -> Error StackOverflowError -> Error NoClassDefFoundError -> Error IOException -> checked Exception InterruptedException -> checked Exception NullPointerException -> unchecked Exception IllegalArgumentException -> unchecked Exception
All errors are unchecked. Exceptions are checked unless they extend RuntimeException.
2. Error vs Exception: Comparison
| Aspect | Error | Exception |
|---|---|---|
| Package / parent | java.lang.Error, extends Throwable | java.lang.Exception, extends Throwable |
| Meaning | Serious problem in the JVM or environment | Problem in the application or its inputs |
| Recoverable? | Usually not | Often yes |
| Checked? | Always unchecked | Checked, except RuntimeException subclasses |
| Should you catch it? | Generally no | Yes, where you can handle it |
| Caused by | Lack of memory, deep recursion, missing classes, JVM failures | Bad input, missing files, network issues, programming bugs |
| Examples | OutOfMemoryError, StackOverflowError, NoClassDefFoundError | IOException, SQLException, NullPointerException |
3. Exceptions: Recover and Continue
Exceptions describe problems that the program can anticipate. Handling them lets the program carry on:
public class RecoverableException {
public static void main(String[] args) {
// An Exception: the program can recover and continue
String[] inputs = {"42", "forty-two", "7"};
int total = 0;
for (String in : inputs) {
try {
total += Integer.parseInt(in);
} catch (NumberFormatException e) {
System.out.println("skipping invalid input: " + in);
}
}
System.out.println("total = " + total);
}
}
skipping invalid input: forty-two total = 49
4. Errors: Something Is Seriously Wrong
Errors are thrown by the JVM when it cannot continue normally. This demo catches two of them only to show what they look like; in real code you would fix the cause (add a base case to the recursion, process data in smaller pieces) instead of catching the error:
public class ErrorDemo {
static int depth = 0;
static void dive() { depth++; dive(); } // no base case
public static void main(String[] args) {
// An Error: caught here only to demonstrate it; real code should fix the cause instead
try {
dive();
} catch (StackOverflowError e) {
System.out.println("StackOverflowError: the call stack ran out after many nested calls");
}
try {
int[] huge = new int[Integer.MAX_VALUE];
System.out.println(huge.length);
} catch (OutOfMemoryError e) {
System.out.println("OutOfMemoryError: " + e.getMessage());
}
}
}
StackOverflowError: the call stack ran out after many nested calls OutOfMemoryError: Requested array size exceeds VM limit
5. Common Errors
| Error | Typical cause | What to do |
|---|---|---|
OutOfMemoryError | Heap full, memory leak, huge allocations | Fix leaks, process data in chunks, increase -Xmx |
StackOverflowError | Unbounded recursion | Add a base case or use iteration |
NoClassDefFoundError | Class present at compile time but missing at runtime | Fix the class path or dependencies |
ExceptionInInitializerError | Exception in a static initializer | Fix the static initialisation code |
UnsatisfiedLinkError | Native library not found | Install the library or fix java.library.path |
AssertionError | Failed assert or "impossible" state | Fix the bug the assertion detected |
6. What Should You Catch?
- Catch specific exceptions you can handle where they occur.
- Do not catch
Errorin normal code. After anOutOfMemoryErrorthe program may be in an unpredictable state. - Avoid
catch (Throwable t); it also catches errors. At the very top of an application (for example a thread's run loop), it may be used to log a crash before exiting. catch (Exception e)does not catch errors, which is one reason it is preferred overThrowablefor catch-all logging.
7. Summary
ErrorandExceptionare the two subclasses ofThrowable.- Errors signal serious JVM or environment problems and are always unchecked; applications usually should not catch them.
- Exceptions signal application-level problems; checked exceptions must be handled, runtime exceptions usually reveal bugs.
- Prevent errors by fixing their causes, and handle exceptions where you can respond meaningfully.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. Are errors checked or unchecked?
Always unchecked. The compiler never requires you to catch or declare an Error.
Q2. Can I catch an Error?
Technically yes, since it is a Throwable, but you should not in normal code. The JVM may be in a bad state, and continuing can cause further problems.
Q3. Is OutOfMemoryError an exception?
No. It is an Error (a subclass of VirtualMachineError), not an Exception, so catch (Exception e) does not catch it.
Q4. What causes StackOverflowError?
A thread's call stack running out of space, almost always because of recursion without a working base case, or extremely deep recursion.
Q5. Does catch (Exception e) catch errors?
No. Only catch (Throwable t) or a catch for a specific error type catches errors.
Q6. What is NoClassDefFoundError?
An error thrown when a class that was available at compile time cannot be found or loaded at runtime, usually because of a missing JAR or a failed static initializer.