Understanding exception hierarchy in Java - a tutorial
This tutorial explains exception hierarchy in Java. It starts with showing the Java class structure for handling errors and exceptions. We will then look at three major types of exceptions in Java which are direct sub-classes of
Important classes of Java Exception Hierarchy
Above class diagram depicts the 4 fundamental classes which are at the heart of exception handling in Java -
Three main types of exceptions in Java
From a programming perspective you will rarely work with Throwable class. Rather, it is considered a good programming practice to avoid using Throwable directly in your code. The remaining three classes - Exception, RuntimeException and Error represent the three important types of exceptions in Java.
Let us take a look at the 3 main types of Exceptions in Java -
java.lang.Exception
, java.lang.RuntimeException
and java.lang.Error
respectively, along with examples for each type.
Java Exception Hierarchy Class Diagram
java.lang.Throwable
is at the root of Java's exception hierarchy. All types of exception are descendants ofThrowable
.java.lang.Exception
is direct sub-class ofThrowable
.Exception
is the root class for all checked exceptions in Java.java.lang.RuntimeException
is direct sub-class ofException
.RuntimeException
is the root class for all unchecked exceptions in Java.java.lang.Error
is direct sub-class ofThrowable
and represents unrecoverable JVM errors.
Let us take a look at the 3 main types of Exceptions in Java -
- Exceptions - Also known as checked exceptions, these are the sub-classes of
java.lang.Exception
class. Whenever a piece of code is likely to throw a checked exception, then either it must be caught using a try-catch block or the signature of the method containing such code should specify this exception in the throws clause. Examples-FileNotFoundException
,IOException
. - Runtime Exceptions - Also known as unchecked exceptions, these are the sub-classes of
java.lang.RuntimeException
. These exceptions are specified for scenarios which neither need to be specifically caught using try-catch block nor do the methods which can throw them need to include these exceptions in the throws clause. Examples-ArrayIndexOutOfBoundsException
,NullPointerException
. - Errors - Errors are sub-classes of
java.lang.Error
class. These exceptions are thrown by JVM when it encounters severe issues such as if it runs out of memory and similar serious error conditions. These errors should not be caught and should be dealt with on priority as they may lead to significant glitches in deployed code. Examples-OutOfMemoryError
,StackOverflowError
.