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
java.lang.Error respectively, along with examples for each type.
Java Exception Hierarchy Class Diagram
Important classes of Java Exception Hierarchy
Above class diagram depicts the 4 fundamental classes which are at the heart of exception handling in Java –
java.lang.Throwableis at the root of Java’s exception hierarchy. All types of exception are descendants of
java.lang.Exceptionis direct sub-class of
Exceptionis the root class for all checked exceptions in Java.
java.lang.RuntimeExceptionis direct sub-class of
RuntimeExceptionis the root class for all unchecked exceptions in Java.
java.lang.Erroris direct sub-class of
Throwableand represents unrecoverable JVM errors.
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.
- Exceptions – Also known as checked exceptions, these are the sub-classes of
java.lang.Exceptionclass. 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.
- 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.
- Errors – Errors are sub-classes of
java.lang.Errorclass. 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.
In this article we first looked at the exception hierarchy in Java described via its class diagram.This was followed by brief explanation of the important classes in the diagram. Finally, we looked the three main types of exceptions in Java – Exceptions, Runtime Exceptions and Errors and understood their individual purpose.
Copyright © 2014-2022 JavaBrahman.com, all rights reserved.