T E C h O C E A N H U B

Let us explore about multiple catch block in Exception Handling in Java. part-3

In the last post we read about try, catch and finally block and their three forms. Now we are going to discuss about how to handle multiple catch blocks while Exception  handling. so let’s see how multiple catch block looks like.

Below there is a code which explains the working of multiple catches. There are 2 scenarios in which multiple catches work.

  //first scenario
  public class UseMultiCatch{
      public static void main(String[] args) {
           int a=7, b=0,c;
           try {
               c=a/b;
           }catch(ArithmeticException e) {
              System.out.println("Exception is"+e);
           } catch(Exception e) {
              System.out.println("Exception is"+e);
           }
      }
 } 
  //Second scenario
  public class Multiple{
     public static void main(String[] args) {
       try{
         int array[]= {2,4,6,7};
         System.out.println("check Value"+array[6]);
       }catch(ArithmeticException e) {
           System.out.println("Arithmetic Exception occurs");
       }catch(ArrayIndexOutOfBoundsException e){
           System.out.println("ArrayIndexOutOfBoundsException occurs "+e);
        }     
        finally {
           System.out.println("Release the variable");
         }
      }
    }

Above both the types focus on how exceptions are handled.

In the first case child exception will be taken first.
In the the next case only one exception will be caught first , despite, you try to put many different exception, but first exception handled by the catch.

There is one important aspect which is normally not been focussed easily and that is if you give your base exception ( base exception class is Exception itself) first before child exception. In that case your child exception will not be taken care by catch block.

Feel free to read and comment below.

Copyright ©TechOceanhub All Rights Reserved.