Java Exception Class Hierarchy

Carvia Tech | September 12, 2020 | 2 min read | 208 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. What is Immutable Class in Java
  3. Is Java Pure Object Oriented Language?
  4. CRC32 checksum calculation Java NIO
  5. How will you handle ConcurrentModificationException in Java
  6. Precision and scale for a Double in java
  7. What is AtomicInteger class and how it works internally


Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info