❮ Previous Next ❯

Chained Exceptions

An application often responds to an exception by throwing another exception. In effect, the first exceptioncausesthe second exception. It can be very helpful to know when one exception causes another. Chained Exceptions help the programmer do this.
The following are the methods and constructors in Throwable that support chained exceptions.

The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. getCause returns the exception that caused the current exception, and initCause sets the current exception's cause.

The following example shows how to use a chained exception.

Example

try
{
}
catch (IOException e)
{
throw new SampleException("Other IOException", e);
}

In this example, when an IOException is caught, a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.
Lets see an example to handle chained exception using multiple catch blocks.

Example

public class ChainedExample
{
public static void main (String args[]) throws Exception
{
int n=20,result=0;
try
{
result=n/0;
System.out.println("The result is"+result);
}
catch(ArithmeticException ex)
{
System.out.println("Arithmetic exception occurred: "+ex);
try
{
throw new NumberFormatException();
}
catch(NumberFormatException ex1)
{
System.out.println("Chained exception thrown manually : "+ex1);
}
}
}

Output

Arithmetic exception occurred :
java.lang.ArithmeticException: / by zero
Chained exception thrown manually :
java.lang.NumberFormatException


❮ Previous Next ❯


  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved