Site icon JavaGoal

Chained exception in java

If you want to relate one exception with another exception, then it is Chained Exceptions in java. By mean of relationships, you can describe one exception is the coming cause of another exception. It provides a better understanding to resolve any problem.

Java supports chained exceptions by using constructors and methods. In java Throwable class have some constructor and method as following: 

Constructors :

Throwable(Throwable cause): cause of exception that causes the current exception.
Throwable(String msg, Throwable cause): You can give a message for providing more under stability and cause of exception that causes the current exception.

Methods:

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

For example: Consider a situation in which throws an ArithmeticException because of an attempt to divide by zero but the actual cause of the exception was number format because we are not all to divide with zero. The method will throw only ArithmeticException. The user would not come to know the actual reasons behind the exception. So now we will be using a chained exception in java in such type of situations.

public class ChainedException
{ 
    public static void main(String[] args) 
    { 
    	int a = 0,b;
        try
        { 
           b = 4/a;           
        } 
  
        catch(ArithmeticException e) 
        { 
          if(a <= 0 )
          {
	     // Setting a cause of the exception 
	    e.initCause(new NumberFormatException("This is actual cause of the exception")); 
          }
          // Getting the actual cause of the exception 
          System.out.println(e.getCause()); 
            
          throw e;  
        }   
    } 
}

Output: java.lang.NumberFormatException: This is actual cause of the exceptionException in thread “main” java.lang.ArithmeticException: / by zero at ChainedException.main(ChainedException.java:9) Caused by: java.lang.NumberFormatException: This is actual cause of the exception at ChainedException.main(ChainedException.java:17)

Exit mobile version