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; }
Or, wrap it within a new exception and throw it. 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 a 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 an 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 the higher exceptions 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(); } }
Output1
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)
Output2
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)