group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
255 Members
Join this group to post and comment.
Gaurav Prasad
Gaurav Prasad
Computer Science
19 Jan 2019

What is multi-catch block in java?

details?

DHIRAJ LOTLIKAR
DHIRAJ LOTLIKAR
Information Technology
2mos ago

What if in a code you by mistake access an element of an array which is not present in array. For example if the array contains 5 elements and you are accessing the sixed element. It will give you an error, because you are trying to access element which is not present in the array. 

If you are using try-catch but you haven't specified the exception then you will get an error. To solve the error or to print error message instead of exception. 

You need to add catch method specifying the exception. In this way you can add multiple catch blocks. You can also add multiple exception in one catch statements. Since you can use this if number of exception wants to print same message.

This concept of having multiple exceptions in one catch  was introduced in 1.7 version. If you are working on 1.6 then it will not work.

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
1mo ago

A try block can be followed by one or more catch block.Each catch block must contain a different exception handler.so if you have to perform different tasks at  the occurrence of different exceptions,use java multi catch block.

1.At a time only one exception occurs and at a time only one catch block is executed.

2.All the catch blocks must be ordered from most specific to  most general i,e. catch for ArithmeticException  must come before catch for exception.

For Example:

public class MultipleBlock

{

   public static void main(String args[])

   {

        try{

               int a[]=new int[5];

              a[5]=30/0;

         }

      catch(ArithmeticException e)

     { 

          System.out.println("Arithmetic Exception Occurs");

      }

     catch(ArrayOutOfBoundsException e)

    {

          System.out.println("ArrayOutOfBounds Exception Occurs");

    }

    catch(Exception e)

  {

      System.out.println("parent exception occurs");

}

      System.out.println("rest of the code");

   }

}

Output: Arithmetic Exception occurs

             rest of the code