All 15 Exceptions questions
More in Exceptions
Advertisement
Java › Exceptions

What is the difference between Error and Exception in Java's Throwable hierarchy, and why should application code generally avoid catching Error subclasses like OutOfMemoryError or StackOverflowError?

Intermediate

Answer

Both Error and Exception extend the common Throwable superclass, but Error is specifically reserved for serious, generally unrecoverable conditions typically caused by the JVM/environment itself running out of critical resources or hitting a fundamental limit (OutOfMemoryError, StackOverflowError, LinkageError) rather than an application-level failure condition; catching these is generally discouraged (though technically possible, since they're not enforced as checked) because the JVM's own internal state may already be significantly compromised by the time such an Error is thrown (for example, after an OutOfMemoryError, there may not be enough free memory remaining to even execute a meaningful recovery/cleanup routine), making genuine recovery unreliable at best and potentially masking a severe underlying problem that should instead cause the application to fail fast and restart cleanly.
try {
    performRecursiveOperation();
} catch (StackOverflowError e) {  // technically legal, but generally a bad idea
    log.error("Stack overflow occurred", e);
    // The JVM's stack state at this point may be in a precarious condition;
    // "recovering" and continuing normal operation is often unreliable
}
Real-world example A team debugging a service that behaves erratically after briefly catching and 'handling' an OutOfMemoryError (attempting to continue normal operation rather than restarting) discovers the JVM's internal state was left in a subtly corrupted condition by the near-exhaustion event, leading them to instead let such Errors propagate uncaught and rely on process supervision (like Kubernetes) to restart the instance cleanly.

Common follow-ups: Are there any legitimate, narrow scenarios where catching a specific Error subclass is genuinely appropriate?;How does this distinction between Error and Exception inform designing a global/top-level exception handler's scope?