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.

published: reading time: 15 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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 Error to resume normal work — serious VM or linkage failures can leave the application unable to continue safely
  • Do not throw Error subclasses — Use RuntimeException or custom exceptions for business logic failures
  • Avoid catching generic Throwable for business recovery — It also catches Error and can hide failures the code cannot fix
  • Do not confuse the hierarchy with the catch set — Exception includes RuntimeException; Throwable also includes Error

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 finally for 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

  1. Swallowing exceptions silently — Empty catch blocks hide failures
  2. Catching Exception too broadly — It also catches RuntimeException; use it only where the boundary can respond
  3. Re-throwing without context — Original exception lost in stack trace
  4. Confusing Error with Exception — Avoid catching Error to resume normal work; infrastructure may report it before failing or rethrowing
  5. Over-relying on checked exceptions — Creates verbose signatures and tight coupling

Quick Recap

  • Throwable is the root of all throwable types
  • Error signals serious abnormal conditions; ordinary application code should not catch it to resume work
  • Exception includes conditions an application may want to handle; recoverability depends on context
  • RuntimeException is 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

1. What is the difference between Error and Exception in Java?
Exception and Error both extend Throwable. `Exception` covers conditions an application may want to catch; it does not guarantee recovery is possible. `Error` indicates a serious abnormal condition that application code generally should not catch to resume normal work. Decide how to respond based on the failure, API contract, and system state."

2. What are checked and unchecked exceptions?
Checked exceptions are subclasses of Exception but not RuntimeException. The compiler requires them to be caught or declared with throws. The checked/unchecked distinction only describes compiler obligations: checked exceptions must be caught or declared, while `RuntimeException` and `Error` subclasses do not. Neither category guarantees whether a caller can recover."

3. Why should you avoid catching generic Throwable?
Catching `Throwable` includes both `Exception` and `Error`, so it is usually too broad for business recovery. Catch a specific type where the current layer can respond. An outer task boundary can report an uncaught failure, but should not swallow an `Error` and continue normal work."

4. What is the Throwable hierarchy in Java?
The hierarchy splits into `Exception` and `Error`. `RuntimeException` extends `Exception` and is unchecked; checked exceptions are its other subclasses. `OutOfMemoryError` and `StackOverflowError` extend `Error`."

5. Should you catch OutOfMemoryError?
Application code generally should not catch `OutOfMemoryError` to resume work. The JVM may be unable to allocate memory, and the error may have no writable stack trace or suppression support. If infrastructure reports it, treat the process state as unreliable and fail or terminate rather than continue normal service."

6. Can you catch both Error and Exception in the same catch block?
A `catch (Throwable)` can receive either type, but it is rarely right for application recovery. Use narrow catches in ordinary code. At a task or process boundary, report the throwable, then let the failed work terminate or rethrow it; catching it does not make the system healthy."

7. How does the compiler enforce checked exception handling?
The compiler tracks checked exceptions — subclasses of Exception that are not RuntimeException subclasses. When a method throws a checked exception, either the caller must catch it in a try-catch block, or the method must declare it in its throws clause. Without this handling, code fails to compile. The rule makes checked exceptions part of a method's compile-time contract; it does not promise that a particular failure is recoverable. A caller may handle it, translate it at a boundary, or propagate it."

8. What is the difference between getMessage() and getLocalizedMessage()?
getMessage() returns the string passed to the exception constructor, useful for debugging. getLocalizedMessage() is intended for locale-specific messages by default it delegates to getMessage() but subclasses can override it to provide localized error descriptions for end users."

9. Why does RuntimeException not require throws declaration?
RuntimeException is an unchecked exception — the compiler does not enforce handling or declaration requirement for any subclasses of RuntimeException or Error. `RuntimeException` still extends `Exception`, and a `catch (Exception)` catches it. Its cause may be invalid input, a programming defect, or another API-defined condition; handle it only at a layer that can respond without hiding a defect."

10. What happens when you catch an exception but do not handle it?
If a catch block catches an exception but performs no action — either no code or just a comment — the exception is silently swallowed. The caller may assume the operation succeeded even though it did not. That can leave state incomplete. Recover according to the API contract, propagate the exception, or translate it while preserving its cause."

11. Can an exception be thrown from a static initializer?
Yes. If a static initializer throws an exception — checked or unchecked — the class is marked as uninitialized. Any attempt to use that class results in an ExceptionInInitializerError (which wraps the original exception). This prevents the class from being used in an invalid state. The wrapped exception can be retrieved via getCause() on the ExceptionInInitializerError."

12. How does exception propagation work with inheritance?
When overriding a method, the overriding method cannot declare new checked exceptions beyond those declared in the parent. It can throw a narrower exception type (a subtype of the parent's exception) or throw none. This ensures that code using the parent type reference still handles all possible exceptions. If a parent declares throws IOException, the child can throw FileNotFoundException but not SQLException."

13. What is the relationship between RuntimeException and Exception?
RuntimeException extends Exception. All RuntimeException subclasses are unchecked — the compiler does not require handling or declaration. The Exception branch splits into checked exceptions (RuntimeException's siblings) and unchecked RuntimeExceptions. This is why catching Exception catches both checked exceptions and RuntimeExceptions unless you specifically exclude RuntimeException."

14. Can you have a try block without catch or finally?
A `try` may have `finally` without `catch`, and an uncaught exception still propagates. For resources that implement `AutoCloseable`, try-with-resources is usually clearer and preserves close failures as suppressed exceptions. Cleanup follows Java control flow; process termination or a forced kill can stop it."

15. How does Throwable relate to the catching hierarchy?
The catch parameter type sets the range: `catch (IOException e)` also catches its subclasses; `catch (Exception e)` catches checked exceptions and `RuntimeException`; `catch (Throwable t)` also catches `Error`. Prefer the narrowest type the current layer can handle."

16. What is ExceptionInInitializerError and when does it occur?
ExceptionInInitializerError wraps an exception thrown during class initialization (static initializers or static field initializers). It prevents the class from being used because initialization failed. The original exception is available via getCause(). This error type itself extends LinkageError, not Exception, meaning it indicates a programming environment problem rather than a runtime failure in normal program logic."

17. Is NullPointerException checked or unchecked?
NullPointerException is unchecked. It extends RuntimeException, which is a subclass of Exception but not a checked exception. The compiler does not require handling or declaration. Whether null is valid depends on the API contract. Validate or reject it at the boundary when needed, and avoid catching an NPE deep inside the code if that would hide a programming defect."

18. What is the fillInStackTrace() method and when is it used?
fillInStackTrace() populates the stack trace for the exception by capturing the current execution stack. It is called automatically when an exception is constructed. You rarely need to call it directly, but doing so before re-throwing an exception transfers the stack trace from the original throw point to the re-throw point — which can hide the real origin of the error. Only use it deliberately."

19. Why should you not catch Error in production code?
Ordinary application code should not catch `Error` to continue normal work. An infrastructure boundary may report an uncaught error or perform narrowly scoped cleanup before it fails or rethrows. With `OutOfMemoryError`, assume the process may not be able to allocate or maintain consistent state; do not resume normal service."

20. How do you choose between checked and unchecked exceptions?
Choose based on the API contract and the caller that can make a useful decision. Checked exceptions make callers catch or declare a condition; unchecked exceptions do not have that compile-time requirement. Neither category guarantees recoverability. Keep catches narrow and translate failures only at a boundary that can add useful context or choose a response."

Further Reading

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.

#java-abstract-classes #java #java-fundamentals

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-arithmetic-operators #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals