Chained Exception
Chained Exception
Example 1:
class ChainExcDemo
{
static void demoproc()
{
// create an exception
NullPointerException e =new NullPointerException("top layer");
// add a cause
e.initCause(new ArithmeticException("cause"));
throw e;
}
public static void main(String args[])
{
try
{
demoproc();
} catch(NullPointerException e)
{
// display top level exception
System.out.println("Caught: " + e);
// display cause exception
System.out.println("Original cause: " +
e.getCause());
}
}
}
OUTPUT:
Caught: java.lang.NullPointerException: top layer
Original cause: java.lang.ArithmeticException: cause
2.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