Java - Exception Class Hierarchy

Introduction

The Java class library contains many exception classes.

The root is the Throwable class in the inheritance hierarchy.

When an exception is thrown, it must be an object of the Throwable class, or its subclasses.

The parameter of the catch block must be of type Throwable, or its subclasses.

The following catch blocks are valid, they use throwable types as a parameter, which are the Throwable class or its subclasses:

Throwable is a valid exception class

catch(Throwable t) {
}

Exception is a valid exception class because it is a subclass of Throwable

catch(Exception e) {
}

IOException class is a valid exception class because it is a subclass of Throwable

catch(IOException t) {
}

ArithmeticException is a valid exception class because it is a subclass of Throwable

catch(ArithmeticException t) {
}

You can create your own exception classes by inheriting your classes from one of the exception classes.

Arranging Multiple catch Blocks

For the following code

try {
        statement1;
        statement2; // Exception of class MyException is thrown here
        statement3;
}
catch (Exception1 e1) {
        // Handle Exception1
}
catch (Exception2 e2) {
        // Handle Exception2
}

Exception1 must be more specific than Exception2

Multiple catch blocks for a try block must be arranged from the most specific exception type to the most generic exception type.

Example

The ArithmeticException class is a subclass of the RuntimeException class.

try {
        // Do something, which might throw Exception
}
catch(ArithmeticException e1) {
        // Handle ArithmeticException first
}
catch(RuntimeException e2) {
        // Handle RuntimeException after ArithmeticException
}

Quiz