Techoceanhub logo

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.

 

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);
        }

  }

 } 

 

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 comment and subscribe my channel.

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .