Java Exception Class Hierarchy

Upasana | September 12, 2020 | 2 min read | 281 views


Throwable sits at the top of Java Exception Class hierarchy. Exception and Error are the two direct subclasses that extends Throwable.

Below is the rough diagram for Java Exception Class Hierarchy.

java exception hierarchy
Java Exception Class Hierarchy

Logically, there are three main types of Exceptions in Java:

Error

It is an irrecoverable condition e.g. OutOfMemoryError, StackoverflowError, AssertionError etc. Right side of Exception Class Tree clearly illustrates Error Hierarchy.

Checked Exceptions

These classes extends Exception class but not part of RuntimeException, example includes: IOException, SQLException, FileNotFoundException, etc. Developers need to declare/catch these exceptions using try-catch block.

Unchecked (Runtime) Exceptions

As illustrated in left most side of Tree in above diagram, anything that extends RuntimeException belongs to this category. It represents an error in our program’s logic which can not be reasonably recovered from at run time, for example NullPointerException, ArrayIndexOutOfBoundsException. We do not need to declare/catch such exception in the method signature because these are not expected by any programmer. A custom unchecked exceptions can be created by extending from RuntimeException.

Questions

Is it possible to catch Exception before catching NullPointerException in single try-catch block?

No, compiler will complain. Lets see the code first.

Java Source

private void method1() {
    try {
        throw new NullPointerException("test");
    } catch (Exception e) {
        e.printStackTrace();
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    }
}

Compiler will report error on this line, because the super class of NullPointerException which is Exception, already has a catch block before NPE.

The correct way would be to move NPE before the exception catch block, as illustrated in the below code snippet.

private void method2() {
    try {
        throw new NullPointerException("test");
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Top articles in this category:
  1. Design an Immutable class that has an java.util.Date member
  2. Secure OTP generation in Java
  3. What is Immutable Class in Java
  4. Fail-Safe vs Fail-Fast Iterator in Java Collections Framework
  5. Is Java Pure Object Oriented Language?
  6. CRC32 checksum calculation Java NIO
  7. Removing elements while iterating over a Java Collection

Recommended books for interview preparation:

Find more on this topic: