Java Examples - Chained exceptions

Advertisements


Problem Description:

How to use catch to handle chained exception?

Solution:

This example shows how to handle chained exception using multiple catch blocks.

public class Main{
   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 occoured: "+ex);
         try {
         throw new NumberFormatException();
         }
         catch(NumberFormatException ex1) {
            System.out.println
            ("Chained exception thrown manually : "+ex1);
         }
      }
   }
}

Result:

The above code sample will produce the following result.

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


Advertisements
Advertisements