The Wayback Machine - https://web.archive.org/web/20240606111532/https://www.geeksforgeeks.org/chained-exceptions-java/
Open In App

Chained Exceptions in Java

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Chained Exceptions allows to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not come to know about the actual cause of exception. Chained Exception is used in such type of situations.  Constructors Of Throwable class Which support chained exceptions in java :

  1. Throwable(Throwable cause) :- Where cause is the exception that causes the current exception.
  2. Throwable(String msg, Throwable cause) :- Where msg is the exception message and cause is the exception that causes the current exception.

Methods Of Throwable class Which support chained exceptions in java :

  1. getCause() method :- This method returns actual cause of an exception.
  2. initCause(Throwable cause) method :- This method sets the cause for the calling exception.

Example of using Chained Exception: 

JAVA




// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
    public static void main(String[] args)
    {
        try
        {
            // Creating an exception
            NumberFormatException ex =
                       new NumberFormatException("Exception");
  
            // Setting a cause of the exception
            ex.initCause(new NullPointerException(
                      "This is actual cause of the exception"));
  
            // Throwing an exception with cause.
            throw ex;
        }
  
        catch(NumberFormatException ex)
        {
            // displaying the exception
            System.out.println(ex);
  
            // Getting the actual cause of the exception
            System.out.println(ex.getCause());
        }
    }
}


Output:

java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

Chained exceptions, also known as nested exceptions, allow you to associate a cause with an exception in Java. This is useful when you want to propagate information about the original cause of an exception.

In Java, you can chain exceptions using the constructor of the Throwable class. Here’s an example:

Java




public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // code that might throw an exception
            int[] numbers = new int[5];
            int divisor = 0;
            for (int i = 0; i < numbers.length; i++) {
                int result = numbers[i] / divisor;
                System.out.println(result);
            }
        } catch (ArithmeticException e) {
            // create a new exception with the original exception as the cause
            throw new RuntimeException("Error: division by zero", e);
        }
    }
}


In this example, an array of integers is defined and a divisor is set to 0. Inside the try block, a for loop is used to divide each element in the array by the divisor. Since dividing by 0 is not allowed, an ArithmeticException is thrown. This exception is caught in the catch block, which creates a new RuntimeException object with the original ArithmeticException object as the cause.

When you run this program, you should see the following output:

Exception in thread “main” java.lang.RuntimeException: Error: division by zero
at ExceptionExample.main(ExceptionExample.java:10)
Caused by: java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:8)
 

As you can see, the RuntimeException object is printed to the console with a message indicating that there was an error caused by division by zero. The stack trace of the original ArithmeticException object is also included as the cause of the exception.

By chaining exceptions, you can provide more information about the original cause of an exception, which can be helpful in debugging and troubleshooting.



Previous Article
Next Article

Similar Reads

Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Checked vs Unchecked Exceptions in Java
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run time, that disrupts the normal flow of the program’s instructions. In Java, there are two types of exceptions: Checked exceptionsUnchecked exceptions Checked Exceptions in Java These are the exceptions that are checked at compile time.
4 min read
Using throw, catch and instanceof to handle Exceptions in Java
Prerequisite : Try-Catch Block in Java In Java, it is possible that your program may encounter exceptions, for which the language provides try-catch statements to handle them. However, there is a possibility that the piece of code enclosed inside the 'try' block may be vulnerable to more than one exceptions. For example, take a look at the followin
4 min read
Java Program to Handle Runtime Exceptions
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, InvalidArgumentException etc. The NullPo
2 min read
Java Program to Handle Divide By Zero and Multiple Exceptions
Exceptions These are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. Handling Multiple exceptions: There are two methods to handle multiple exceptions in java. Using a Single try-catch block try statement allows you to define a block of code to be tested f
3 min read
Java Program to Use Exceptions with Thread
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught by handlers(here catch block). Exceptions are caug
5 min read
Java Program to Use finally block for Catching Exceptions
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not. There are 3 possible cases where final
3 min read
Top 5 Exceptions in Java with Examples
An unexpected unwanted event that disturbs the program's normal execution after getting compiled while running is called an exception. In order to deal with such abrupt execution of the program, exception handling is the expected termination of the program. Illustration: Considering a real-life example Suppose books requirement is from Delhi librar
5 min read
User Defined Exceptions using Constructors in Java
In Java, we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException. In Java, we can create our own exception class and throw that exception using throw keyword. These
3 min read
How to Solve Class Cast Exceptions in Java?
An unexcepted, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Example: If our program requirement is to read data from the remote file locating at the U.S.A. At runtime, if the remote file is not available then we will get RuntimeExcept
3 min read
Article Tags :
Practice Tags :