Tuesday, April 17, 2018

Explain Java Exception Class Hierarchy

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 Class Hierarchy
Logically, there are three main types of Exceptions in Java:
Error
It is an irrecoverable condition e.g. OutOfMemoryErrorStackoverflowErrorAssertionError 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:  IOExceptionSQLExceptionFileNotFoundException, 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.

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();
    }
}

No comments:

Post a Comment

Your comment will be published after review from moderator