Throwable Hierarchy: Error vs Exception in Java
Understand Java's Throwable hierarchy, the distinction between Error and Exception, and when each category should be handled differently.
Understand Java's Throwable hierarchy, the distinction between Error and Exception, and when each category should be handled differently.
Throwable Hierarchy: Error vs Exception in Java
Java’s exception handling framework has one root class: Throwable. Every object thrown in Java is an instance of this class or one of its subclasses. Its type tells you how the compiler treats it; the failure and the state of the application determine what to do next.
Introduction
The hierarchy helps explain which failures a method can declare and which types a catch block can receive. It does not, by itself, tell you whether an application can recover.
The hierarchy splits into Error and Exception. The Java API describes an Error as a serious abnormal condition that an application generally should not try to catch for normal recovery. A failure such as OutOfMemoryError can leave the process unable to allocate memory or trust its current state. Exception covers conditions an application may want to catch, but the type does not guarantee that recovery is possible.
The checked/unchecked distinction is a compiler rule. A checked exception must be caught or declared; RuntimeException and Error subclasses do not have that requirement. A checked exception is not automatically recoverable, and an unchecked exception is not automatically impossible to handle. Choose where to catch based on the API contract and which layer can respond meaningfully.
This guide covers the full hierarchy, the checked/unchecked distinction and when each applies, the common mistakes of catching Error or generic Throwable, and the implications for exception handling design in application code.
When to Use
You will encounter the Throwable hierarchy when:
- Catching built-in Java exceptions (
NullPointerException,IllegalArgumentException) - Choosing where a failure can be handled or reported
- Understanding framework error handling behavior
- Designing application-specific exception types
try {
Integer.parseInt("not-a-number");
} catch (NumberFormatException e) {
// Handle recoverable input validation error
System.err.println("Invalid number format: " + e.getMessage());
}
When NOT to Use
Avoid these common mistakes:
- Do not catch
Errorto resume normal work — serious VM or linkage failures can leave the application unable to continue safely - Do not throw
Errorsubclasses — UseRuntimeExceptionor custom exceptions for business logic failures - Avoid catching generic
Throwablefor business recovery — It also catchesErrorand can hide failures the code cannot fix - Do not confuse the hierarchy with the catch set —
ExceptionincludesRuntimeException;Throwablealso includesError
Throwable Hierarchy Diagram
classDiagram
class Throwable {
+String message
+Throwable cause
+void printStackTrace()
+String getMessage()
+Throwable getCause()
}
class Error {
<<Error>>
+void printStackTrace()
}
class Exception {
<<Exception>>
+void printStackTrace()
}
class RuntimeException {
<<RuntimeException>>
+void printStackTrace()
}
class IOException {
<<checked>>
+void printStackTrace()
}
class SQLException {
<<checked>>
+void printStackTrace()
}
class NullPointerException {
<<RuntimeException>>
+void printStackTrace()
}
class IllegalArgumentException {
<<RuntimeException>>
+void printStackTrace()
}
class OutOfMemoryError {
<<Error>>
+void printStackTrace()
}
class StackOverflowError {
<<Error>>
+void printStackTrace()
}
Throwable <|-- Error
Throwable <|-- Exception
Exception <|-- RuntimeException
Exception <|-- IOException
Exception <|-- SQLException
RuntimeException <|-- NullPointerException
RuntimeException <|-- IllegalArgumentException
Error <|-- OutOfMemoryError
Error <|-- StackOverflowError
Hierarchy Explained
| Type | Category | Checked? | Typical Use |
|---|---|---|---|
Throwable |
Base class | — | Root of all throwable types |
Error |
Serious conditions | No | Usually not handled for normal recovery |
Exception |
Application failures | Yes/No | Depends on type, contract, and system state |
RuntimeException |
Programming errors | No | Bugs (NPE, illegal arguments) |
IOException |
I/O failures | Yes | External resource failures |
SQLException |
Database failures | Yes | JDBC operation failures |
Checked vs Unchecked
Checked exceptions (subclasses of Exception other than RuntimeException) must be caught or declared with throws. This gives callers a compile-time obligation, but it does not mean every such failure is recoverable. Use checked exceptions when the API contract benefits from requiring callers to consider a condition.
Unchecked exceptions include RuntimeException and Error subclasses. The compiler does not require callers to catch or declare them. Runtime exceptions often signal invalid arguments or state, but a boundary may still validate, translate, or report one when the API contract calls for it.
Catch the narrowest type the current layer can handle. Use try-with-resources to close AutoCloseable resources whether the body succeeds or throws; cleanup should not depend on catching an exception. At an application or task boundary, report an uncaught failure through the relevant handler or supervisor, then let the failed task or process stop when it cannot safely continue.
Common checked types include IOException, SQLException, ClassNotFoundException, and ParseException. Their cause and possible response depend on the operation. Common unchecked types include NullPointerException, IllegalArgumentException, IndexOutOfBoundsException, and NumberFormatException; the right response depends on whether the input is expected, where it entered the system, and what the API promises.
// Checked — compiler requires handling
public void readFile(String path) throws IOException {
Files.readString(Path.of(path));
}
// Unchecked — no compiler enforcement
public void divide(int a, int b) {
if (b == 0) throw new ArithmeticException("Division by zero");
}
Failure Scenarios
// Scenario 1: Do not catch an Error and continue normal work
try {
recursiveMethod();
} catch (Error e) {
// If infrastructure must catch it for reporting or cleanup, fail or rethrow.
throw e;
}
// Scenario 2: An outer task boundary reports a failure, then rethrows it.
static void runAtTaskBoundary() throws Throwable {
try {
riskyOperation();
} catch (Throwable failure) {
reportFailure(failure); // Application-specific reporting hook.
throw failure;
}
}
// Scenario 3: Catching checked vs unchecked (CORRECT)
try {
Integer.parseInt("abc");
} catch (NumberFormatException e) {
// A narrow catch can report invalid input at this boundary.
System.out.println("Invalid input: " + e.getMessage());
}
Try-with-resources is the usual choice for closing files, streams, and other AutoCloseable resources. For uncaught failures, a thread’s uncaught-exception handler can report the thread and throwable; a supervisor can decide whether the process should restart. Reporting an Error does not make it safe to resume normal application work (Thread.UncaughtExceptionHandler API).
Trade-off Table
| Approach | Pros | Cons |
|---|---|---|
Catch Exception |
Handles checked and runtime exceptions at a boundary | Can be too broad for local recovery |
| Catch specific types | Precise handling | Requires deciding which failures to handle |
Catch Throwable |
Can report any uncaught throwable at an outer boundary | Includes serious Error conditions |
| Propagate unchecked | Avoids forcing a compile-time catch | Caller still needs a clear API contract |
| Propagate checked | Compiler requires callers to consider it | Adds signatures through call chains |
Security Notes
- Do not expose stack traces in production —
printStackTrace()writes to standard error, which may be logged to files accessible to attackers - Sanitize exception messages before logging — Do not include passwords, session tokens, or PII in error messages
- Avoid exception tunneling — Converting checked exceptions to unchecked without documenting the failure mode obscures error handling
- Failure reporting — An uncaught exception handler can record a failed thread; use try-with-resources or
finallyfor cleanup instead of relying on a catch block
// SECURE: Log without exposing stack trace details
try {
processUserData();
} catch (IOException e) {
logger.error("User data processing failed: {}", e.getClass().getName());
// Do NOT log sensitive details; propagate if this layer cannot recover.
throw e;
}
Common Pitfalls
- Swallowing exceptions silently — Empty catch blocks hide failures
- Catching
Exceptiontoo broadly — It also catchesRuntimeException; use it only where the boundary can respond - Re-throwing without context — Original exception lost in stack trace
- Confusing Error with Exception — Avoid catching
Errorto resume normal work; infrastructure may report it before failing or rethrowing - Over-relying on checked exceptions — Creates verbose signatures and tight coupling
Quick Recap
Throwableis the root of all throwable typesErrorsignals serious abnormal conditions; ordinary application code should not catch it to resume workExceptionincludes conditions an application may want to handle; recoverability depends on contextRuntimeExceptionis unchecked, which means the compiler does not require a catch or declaration- Checked exceptions require handling or declaration; unchecked do not
- Catch narrow types where the current layer can respond; use process-level handlers for uncaught-failure reporting
- Use try-with-resources for cleanup, and do not assume normal work can continue after a fatal VM error
Interview Questions
Further Reading
- Try-Catch-Finally — basic exception handling syntax
- Throw and Throws — throwing and declaring exceptions
- Custom Exceptions — creating application-specific exception types
- Try With Resources — automatic resource cleanup with AutoCloseable
- Exception Best Practices — when and how to use exceptions effectively
- Oracle Java API:
Throwable,Exception,Error, andOutOfMemoryError
Conclusion
The Throwable hierarchy classifies failures and determines which exceptions the compiler requires callers to acknowledge. Error usually calls for failing safely rather than catching it to resume work. Exception describes conditions an application may want to handle, but the type alone does not say whether recovery is possible.
Catch a specific type where the current layer can respond, and use try-with-resources for cleanup. If a failure escapes a task or thread, report it through an uncaught-exception handler or supervisor. For a fatal VM error, especially OutOfMemoryError, treat application state as unreliable and do not continue normal service. See Try-Catch-Finally for control flow and Try With Resources for cleanup.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.