Skip to main content

Exception Hierarchy

In Java, all errors and exceptions are objects. The root of the exception hierarchy is the Throwable class, which belongs to the java.lang package.

The Throwable Class

The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine (JVM) or can be thrown by the Java throw statement.

Throwable has two main subclasses:

  1. Error
  2. Exception

Visualizing the Hierarchy

Here is a visual representation of the Java Exception Hierarchy:


Breakdown of Key Classes

1. Error

An Error indicates a serious problem that a reasonable application should not try to catch. These are abnormal conditions that typically occur in the environment in which the application is running (e.g., the JVM).

  • Examples: OutOfMemoryError, StackOverflowError, VirtualMachineError.
  • Handling: Generally, you do not write catch blocks for Errors because they are irrecoverable.

2. Exception

The Exception class and its subclasses indicate conditions that a reasonable application might want to catch and recover from.

  • Examples: IOException, SQLException, RuntimeException.
  • Handling: You handle these using try-catch blocks to prevent the program from crashing.

3. RuntimeException

RuntimeException is a very special subclass of Exception. It represents exceptions that occur during the normal operation of the Java Virtual Machine.

  • Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.
  • Significance: Exceptions under RuntimeException are known as Unchecked Exceptions, while all other Exception subclasses are known as Checked Exceptions. We will dive into these categories in the next section.