Chained Exceptions in Java allow associating one exception with another, i.e. one exception describes the 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 root cause of the error was an I/O failure that caused the divisor to be zero.
In such cases, chained exceptions help propagate both the primary and underlying causes of the error.
Example: The following example demonstrates how to use chained exceptions in Java.
Output
Caught Exception: java.lang.NumberFormatException: Primary Exception
Cause of Exception: java.lang.NullPointerException: Root cause of the exception
Note: Chained exceptions, also known as nested exceptions, allow us to associate a cause with an exception in Java. This is useful when we want to propagate information about the original cause of an exception.
Constructors
Throwable(Throwable cause): Where cause is the exception that causes the current exception.
Throwable(String msg, Throwable cause): Where msg is the exception message and cause is the exception that causes the current exception.
Methods of Throwable Supporting Chained Exceptions
getCause(): This method returns actual cause of an exception.
Explanation: In this example, an array of integers and sets the divisor to 0.
Inside the try block, it try to divide each element of the array by 0, which throws an ArithmeticException.
This ArithmeticException is caught in the catch block, where a new RuntimeException is created with the original exception i.e. ArithmeticException as its cause.
Since the RuntimeException is not caught, which displays the stack trace, including the RuntimeException and the ArithmeticException.
Advantages of Chained Exceptions:
The advantages of chained exceptions are listed below:
This exception helps in debugging by providing details about both primary and root causes.
It simplifies error handling by enabling propagation of complete exception context.
This improves traceability of errors in complex applications.
Disadvantages of Chained Exceptions:
If not used properly, it can make the stack trace longer and harder to read.
Overuse may cause confusing error messages if exceptions are chained unnecessarily.
Developers must ensure meaningful causes are linked; otherwise, it can mislead during debugging.