Prerequisite
Chained Exception allows to relate one exception with another exception, i.e one exception describes cause of another exception. Chained Exception is used in such type of situations.
In below example, consider a situation in which a method throws an IllegalArgumentException with message “passing Argument is not valid” but the actual cause of exception was an ArithmeticException because of an attempt to divide by zero The method will throw only IllegalArgumentException to the caller. So the caller would not come to know about the actual cause of exception and will see only generic message.
Constructors Of Throwable class
- Throwable(Throwable cause) : Where cause is the exception that causes the current exception.
- Throwable(String message, Throwable cause) : Where message is the exception message and cause is the exception that causes the current exception.
Methods Of Throwable class
- getCause() method:This method returns actual cause of an exception.
- initCause(Throwable cause) method:This method sets the cause for the calling exception.
Example of using Chained Exception
public class ChainedExceptionExample { public static void main(String[] args) { try { int totalAge = 500; int numberOfPerson = 0; int averageAge = averageAge(totalAge, numberOfPerson); System.out.println("Average Age :" + averageAge); } catch (Exception ex) { System.out.println(ex); ex.printStackTrace(); } } public static int averageAge(int totalAge, int numberOfPerson) { int avarageAge; try { /** * ArithmaticException can happen here because of value value * NumberOfPerson as 0 */ avarageAge = totalAge / numberOfPerson; } catch (Exception ex) { System.out.println(ex); // Actual Exception /** * Exception Chaining here by relating this ArithmaticException to * IllegalArgumentException */ throw new IllegalArgumentException("Passing argument is not valid", ex.getCause()); } return avarageAge; } }Output
java.lang.ArithmeticException: / by zero java.lang.IllegalArgumentException: Passing argument is not valid java.lang.IllegalArgumentException: Passing argument is not valid at com.customexceptions.ChainedExceptionExample.testMethod1(ChainedExceptionExample.java:23) at com.customexceptions.ChainedExceptionExample.main(ChainedExceptionExample.java:9)Know More
To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links: s
You must log in to post a comment.