Home » Core Java » Exceptions Hierarchy and Custom Exceptions in Java

About Ilias Koutsakis

Ilias has graduated from the Department of Informatics and Telecommunications of the National and Kapodistrian University of Athens. He is interested in all aspects of software engineering, particularly data mining, and loves the challenge of working with new technologies. He is pursuing the dream of clean and readable code on a daily basis.

Exceptions Hierarchy and Custom Exceptions in Java

Exceptions are a vital part of every modern programming language, as it is a way to handle error cases and unexpected behavior, without necessarily terminating the whole application. Except for that, by handling the exceptions in the correct way, we can get meaningful feedback regarding what went wrong, why and where. As you can understand, it is very important for every Java programmer to have a good grasp of how Exceptions work.

In this post, we are going to take a look at the exception hierarchy, and explain the different kinds of exceptions that exist, the connections between each other and the different ways to approach them.

 

1. Exception hierarchy

Let’s take a look at the main Exception hierarchy diagram in Java:

The main exception hierarchy in Java.

The main exception hierarchy in Java.

As we can see, there are three main classes that are used in order to define the application’s activity after some kind of error has occurred. These are:

  • Throwable: This is the superclass of every possible exception or error that can occur in Java. Throwable and its subclasses (Exception and Error), are the only classes in Java that can be thrown (as exceptions) and caught afterwards. Throwable itself is not usually used in production code and its subclasses are much more common.
  • Error: Error is a subclass that defines a problem, that the application cannot recover from. Most of these errors are very serious, such as IOError, and we define these as errors because we are not supposed to catch them in any way and try to continue any of the application’s operations.
  • Exception: This is the most common class used for error handling. Exceptions are not only recoverable, but are supposed to happen in certain contexts (e.g. connection exceptions happen all the time, so the application is supposed to try to reconnect and establish the connection). One could say that exceptions are usually errors that we can fix on runtime, although this is not always the case, e.g. NullPointerException, which could cause serious problems.

Fortunately, Java not only has a variety of built-in Exception subclasses, specifically designed for certain situations (IOException, IllegalArgumentExceptionNullPointerException etc), but also allows us to create our own Exception classes to accommodate our needs and the needs of our application.

2. Custom Exception creation

As said before, we can easily extend the Exception class in order to create our own custom exceptions, depending on what needs to be checked in our application. In the example that follows, we created a simple custom exception that takes the input of our program into consideration and behaves accordingly. Let’s go then!

WrongCarLengthException.java

public class WrongCarLengthException extends Exception {
    
    public WrongCarLengthException() {
        super("Wrong car length Exception initiated.");
    }
}

CustomExceptionExample.java

import java.util.Scanner;

public class CustomExceptionExample {

    public static void main(String[] args) {
        System.out.println("Please give a car size (between 6 - 10):");
        
        // Get the car length through the stdin.
        Scanner in = new Scanner(System.in);
        int carLength = in.nextInt();
        
        try {
            // We want an exception to be thrown every time the
            // length is out of certain bounds.
            if (carLength < 6 || carLength > 10) {
                throw new WrongCarLengthException();
            }
            
            // Else, we continue the program without exceptions.
            System.out.println("The number is correct, no exception thrown.");
            
        } catch (WrongCarLengthException ex) {
            ex.printStackTrace();
            System.out.println("This exception was caught.");
        }
    }
}

Output

The output should be different depending on our input. So, if the number is between 6 and 10 there should be no exception, and if the number is any other number our custom WrongCarLengthException should be thrown and caught accordingly. Indeed, if we check two different executions of the program we get:

1. Inside our bounds (No exception).

Please give a car size (between 6 - 10):
8
The number is correct, no exception thrown.

2. Outside the bounds (Exception triggered).

Please give a car size (between 6 - 10):
3
WrongCarLengthException: Wrong car length Exception initiated.
This exception was caught.
	at CustomExceptionExample.main(CustomExceptionExample.java:16)

There are many other cases in which we can implement our own exceptions and redirect our workflow in the best way possible. Most of the time however, the API that we will use will have all the needed exceptions built-in so we can depend on these.

3. Download the example

This was an example of the exception hierarchy in Java and the way to create our own custom exceptions.

Download
You can download the full source code of this example here : CustomExceptionExample

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments