Explain Exceptions hierarchy in java?

In Java, exceptions are organized in a class hierarchy rooted at the Throwable class. This structure helps developers understand which types of problems can be caught and handled, and which ones should be avoided or allowed to crash the program.

🌳 Java Exception Hierarchy Overview

                Object
                   |
               Throwable
               /       \
           Error      Exception
                        /     \
         Checked Exceptions  Unchecked Exceptions (RuntimeException)

Object | Throwable / \ Error Exception / \ Checked Exceptions Unchecked Exceptions (RuntimeException)

🔹 1. Throwable (Base Class)

  • The superclass of all errors and exceptions in Java.
  • Only objects that are instances of Throwable (or its subclasses) can be thrown or caught.

🔸 2. Error

  • Represents serious problems that applications should not try to handle.
  • Examples:
  • OutOfMemoryError
  • StackOverflowError
  • VirtualMachineError

These are typically caused by the JVM or system environment and are not meant to be caught in normal code.

🔸 3. Exception

  • Represents conditions that a program might want to catch.
  • Divided into:
  • Checked Exceptions
  • Unchecked Exceptions (RuntimeException)

✅ Checked Exceptions

  • Must be either caught or declared in the method signature using throws.
  • Examples:
  • IOException
  • SQLException
  • FileNotFoundException
  • ClassNotFoundException

These are typically external issues (e.g., file not found, database error) that the program can recover from.

⚠️ Unchecked Exceptions (RuntimeException)

  • Do not need to be declared or caught.
  • Occur due to programming errors.
  • Examples:
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • IllegalArgumentException
  • ArithmeticException

These are often bugs in the code and should be fixed rather than caught.

🧠 Summary Table

TypeSubclass OfMust Handle?Examples
ErrorThrowable❌ NoOutOfMemoryError, StackOverflowError
Checked ExceptionException✅ YesIOException, SQLException
Unchecked ExceptionRuntimeException❌ NoNullPointerException, ArithmeticException

Leave a Reply

Your email address will not be published. Required fields are marked *