Exception Chaining in Java

Exception chaining in java allows us to relate one exception to another exception. An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this.

The Throwablehas below methods that support exception chaining.

You can pass Throwable object to another Throwable constructor or the initCause() method, so that the original exception is propagated to other exception.

Exception Chaining in Java Example

In the below example we have a method getBasicSalary() which throws an MultiplyZeroException. We have another method getEmployeeTotalSalary() which uses getBasicSalary() and catches the exception. But getEmployeeTotalSalary() throws another exception. While throwing the exception we chaining it with the old exception. So when we try to print the exception and its cause we get the entire chained exception details. Also we have printed the stack trace which also give the chained exception details.
WrongSalaryException and MultiplyZeroException are the user defined exceptions,

Output

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn