Java Exception Hierarchy

Java Exception Hierarchy

As shown in the exception hierarchy, a Throwable class is a superclass of all errors and exceptions in Java. Objects those are instances of Throwable or one of its subclasses are thrown by JVM or by Java throw statement.

An Error is a subclass of Throwable that represents serious errors that can’t be handled. A method is not required to declare throws clause for Error or any of its subclasses for the errors thrown during execution of the method but not caught.

Error and its subclasses are unchecked exceptions.
Here are the examples of errors: OutOfMemoryError, StackOverflowError, AssertionError, IOError, NoClassDefFoundError etc.

Exception is a subclass of Throwable. Exception and its subclasses represent the problems from which a program can recover and should be handled by the application.
Exception has two sub type:

1. RunTimeException or Unchecked Exception:
The classes that extends RunTimeException are called unchecked Exception. An unchecked exception occurs at run-time, it can’t be checked at compile time, an application should handle these exceptions. For example: NullPointerException, ArithmeticException, IllegalArgumentException, IndexOutOfBoundException etc.

2. Checked Exception:
The classes that extends Throwable class except RunTimeExpception and Error are called Checked Exception. Checked exception are checked at compile time and application should handle these exceptions. For example: IOException, SQLException, FileNotFoundException, ClassNotFoundException, NoSuchMethodException etc.

User-defined custom exception:
We can also create our own exception. Here are few rules:
1. All exception must be a child of Throwable.
2. To create a RuntimeException, we need to extend the RunTimeException class.
3. To create the checked exception, we need to extend the Exception class.


Related Articles

Leave a Reply

Be the First to Comment!