Sunday, 8 February 2015

Multiple Catch Block In Exception Handling In java

1.  We can use multiple catch block for exception handling.

Syntax:

try {
}
catch () {
}
catch () {
}
catch () {
}

Example :


public class MultipleCatch {
public static void main(String[] args) {
int []arr=new int[5];

try {
             
arr[10]=100;
}
catch (ArithmeticException e) {
System.out.println(e);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}

}
}



Output:

java.lang.ArrayIndexOutOfBoundsException: 10

2:     Remember that when we use multiple catch block , use catch block down to top hierarchy. 
   Because in java unreachable code gives error. 

  
  public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (Exception e) {
            System.out.println(e);
        }
         catch (IndexOutOfBoundsException e) {
                System.out.println(e);
        } 
          
       }

Output:
Unreachable catch block for IndexOutOfBoundsException. It is already handled by the catch block for Exception 

3.  The right way of uses multiple catch block is use first specific catch handle then use  standard catch handle.(i.e. down  to top ).

Example:

public class simple_example {

        public static void main(String[] args) {
           int i=10;
           int j=0;
           try {
               System.out.println("i/j="+i/j);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("index out of bound"+e);
        }
         catch (ArithmeticException e) {
                System.out.println("Arithmetic="+e);
        } 
         catch (Exception e) {
             System.out.println(e);
        } 
           
       }
}

Output:

Arithmetic=java.lang.ArithmeticException: / by zero










No comments:

Post a Comment