Chained Exception in Java

Using chained exception in Java you can associate one exception with another. Chained exception helps in the scenario where one exception causes another exception. The exception that will be thrown is the second exception in such scenario but you can set the cause of original exception in the second exception so in a way you are chaining the exceptions.

As example – You are writing a code where two arguments are passed and then you convert those arguments to integer. In case two arguments are not passed that will result in ArrayIndexOutOfBoundsException but the real cause here is having not enough arguments. So you can set the cause as IllegalArgumentException with the appropriate message.

Constructors and Methods for chained exception in Java

In Throwable class there are two constructors that support chained exception.

  • Throwable(Throwable expObj) – Here expObj signifies the exception that caused the current exception.
  • Throwable(String msg, Throwable expObj) – With this constructor you can also pass an appropriate message along with the exception.

In Throwable class there are two methods that support chained exception.

  • Throwable getCause() – This method returns the underlying exception that caused the current exception.
  • Throwable initCause(Throwable) – This method sets the current exception’s cause. The Throwable argument to initCause is the exception that caused the current exception.

Example Java code demonstrating chained exception

Let’s write Java code for the example already stated above. In the code you expect two arguments are passed and then those arguments are converted to integer.

Output when the code is executed without passing any argument-

Real usage of chained exception

Real usage of chained exception in Java is in the case when you don’t want to propagate layer specific exception to another layer but still want to retain the original exception. This is also one of the best practice for exception handling.

As example – If SQLException is caught in your DB layer, there is no sense in letting the same exception propagate to your business layer. In this case best thing to do is catch the SQLExcpetion (checked exception) in your DAO layer and rethrow another exception (unchecked) that should propagate to business layer. You should send the original exception instance as a parameter.

Reference : https://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html

That’s all for the topic Chained Exception in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.