Wednesday, November 20, 2024
Google search engine
HomeLanguagesJavaChained Exceptions in Java

Chained Exceptions in Java

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

This article is contributed by Pratik Agarwal. If you like Lazyroar and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments