What is chained exceptions in java?

Chained exceptions allow one exception to be associated with another exception, that is, one exception describes the cause of another exception. For example, consider a situation where the method throws an ArithmeticException due to an attempt to divide by zero, but the actual cause of the exception is an I/O error, which causes the division to be zero. This method will only throw ArithmeticException to the caller. So the caller will not know the actual cause of the exception. Chained exceptions are used in this type of situation.

Constructors Of Throwable class Which support chained exceptions in java :

  1. Throwable(Throwable cause) :- Where cause is that the exception that causes the present exception.
  2. Throwable(String msg, Throwable cause) :- Where msg is that the exception message and cause is that the exception that causes the present exception.

Methods Of Throwable class Which support chained exceptions in java :

  1. getCause() method :- This method returns actual cause of an exception.
  2. initCause(Throwable cause) method :- This method sets the cause for the calling exception.

Example of using Chained Exception:

// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
	public static void main(String[] args)
	{
		try
		{
			// Creating an exception
			NumberFormatException ex =
					new NumberFormatException("Exception");

			// Setting a cause of the exception
			ex.initCause(new NullPointerException(
					"This is actual cause of the exception"));

			// Throwing an exception with cause.
			throw ex;
		}

		catch(NumberFormatException ex)
		{
			// displaying the exception
			System.out.println(ex);

			// Getting the actual cause of the exception
			System.out.println(ex.getCause());
		}
	}
}

Output:

java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception

 

Submit Your Programming Assignment Details