What are chained exceptions in Java?

Java 8Object Oriented ProgrammingProgramming

When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects).

While re-throwing exceptions you can throw the same exception as it is without adjusting it as −

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArithmeticException e) {
   throw e;
}

Chained exceptions

You can also wrap a catched exception within a new exception and throw it (in the catch block). When you do so, the first exception is responsible for the second exception i.e. one exception causes the other.

Therefore, when you wrap a cached exception within another exception and throw it, it is known as exception chaining or, exception wrapping, by doing this you can adjust your exception, throwing higher level of exception maintaining the abstraction.

try {
   int result = (arr[a])/(arr[b]);
   System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
}catch(ArrayIndexOutOfBoundsException e) {
   throw new IndexOutOfBoundsException();
}

Example

In the following Java example our code in demoMethod() might throw ArrayIndexOutOfBoundsException and ArithmeticException. We are catching these two exceptions in two different catch blocks.

In the catch blocks we are re-throwing both exceptions one by wrapping within higher exception and the other one directly.

import java.util.Arrays;
import java.util.Scanner;
public class RethrowExample {
   public void demoMethod() {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         throw new IndexOutOfBoundsException();
      }catch(ArithmeticException e) {
         throw e;
      }
   }
   public static void main(String [] args) {
      new RethrowExample().demoMethod();
   }
}

Output

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
4

Exception in thread "main" java.lang.ArithmeticException: / by zero
at myPackage.RethrowExample.demoMethod(RethrowExample.java:16)
at myPackage.RethrowExample.main(RethrowExample.java:25)

Output

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
124
5
Exception in thread "main" java.lang.IndexOutOfBoundsException
at myPackage.RethrowExample.demoMethod(RethrowExample.java:17)
at myPackage.RethrowExample.main(RethrowExample.java:23)
raja
Published on 07-Aug-2019 12:05:55
Advertisements