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. What is the difference between Error and Exception in Java?
Both extend Throwable. An Error indicates a serious problem in the JVM or environment that applications usually cannot recover from. An Exception indicates a condition the application can anticipate and often handle.
Q2. Are errors checked or unchecked?
Always unchecked. The compiler never requires you to catch or declare an Error.
Q3. 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.
Q4. Is OutOfMemoryError an exception?
No. It is an Error (a subclass of VirtualMachineError), not an Exception, so catch (Exception e) does not catch it.
Q5. 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.
Q6. What is the common parent of Error and Exception?
java.lang.Throwable, which itself extends Object.
Q7. Does catch (Exception e) catch errors?
No. Only catch (Throwable t) or a catch for a specific error type catches errors.
Q8. 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.
Q9. Is AssertionError an Error?
Yes. It is thrown by failed assert statements (when assertions are enabled with -ea) and is sometimes thrown manually for situations that should be impossible.
Q10. Can I create my own Error subclass?
You can, but you should not. Errors are reserved for the JVM. Create custom exceptions by extending Exception or RuntimeException.
Q11. Why are errors not recoverable?
They signal that the JVM itself cannot continue reliably: memory is exhausted, the stack is full, or code cannot be loaded. The application has no reliable way to repair these conditions from inside.
Q12. How do I prevent OutOfMemoryError?
Find and fix memory leaks (objects kept in collections or caches), process large data in streams or chunks, and size the heap appropriately with -Xmx. Heap dumps and profilers help locate the problem.
Q13. Is it okay to catch Throwable?
Only in rare top-level code, for example to log a fatal problem before a thread dies. In ordinary code, catch specific exceptions.
Q14. Are RuntimeExceptions errors?
No. RuntimeException is a subclass of Exception. Like errors they are unchecked, but they represent application-level problems, usually bugs.
Q15. What is ExceptionInInitializerError?
An error thrown when a static initializer or static field initialisation throws an exception. The original exception is available as its cause, and the class cannot be used afterwards.
Q16. What is VirtualMachineError?
A subclass of Error for JVM breakdowns, including OutOfMemoryError, StackOverflowError and InternalError.
Q17. Do errors have stack traces?
Yes, like all Throwable objects. A StackOverflowError stack trace is usually very long and repetitive, which points directly to the recursive method.
Q18. Can a program continue after an Error?
Sometimes it technically can, for example after a StackOverflowError in one deep call, but the safe approach is to log the problem and restart or fix the cause.
Q19. Is IOException an error?
No. Despite describing input/output failures, it is a checked Exception, because programs can and should handle it, for example by reporting a missing file.
Q20. Which is more serious, Error or Exception?
Error. It indicates problems with the runtime environment itself, while exceptions describe problems within the application's normal operation.