How to use catch to handle chained exception in Java



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

The following is an another example of use catch to handle chained exception in Java

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{  
            int data = 50/0;  
         }catch(ArithmeticException e){System.out.println(e);}  
            System.out.println("rest of the code...");  
      }
   }
}

The above code sample will produce the following result.

Arithmetic exception occoured: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
rest of the code...
java_exceptions.htm
Advertisements