Multicatch in Java with example

In this tutorial, I’ll show how to use multicatch in Java. Let’s get started.

Java Multicatch block

When we execute java code, There is a chance that different errors can occur: Logical error, syntax error, compile-time error. when an error occurs java compiler will throw a message in the form of an exception.

Java try block allows you to check for errors while the program is executed. If any error occurs then there is a catch block for each try block which can catch the exception thrown by try block.

There can be multiple catch block for a single try block which can handle multiple exceptions at the same time. If an exception occurs then control of execution is passed to the matching catch block of try block.

Steps how JVM performs try-catch block:

First JVM checks whether an exception is handled or not. If not then default handler provided by JVM which performs the further task. If the exception is handled by the user then flow of execution is will not disturb. If there is no exception thenTry-Catch block is completely ignored.

See the Java code below:

{

  public static void main(String[] args) 
  {
    try
    {
    int x=100;
    System.out.println((x/10));
    int arr[]=new int[5];
    arr[6]=40;
    System.out.println((x/0));
    }
    catch(ArithmeticException e)
    {
      System.out.println(e);
    }
    
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println(e);
    }
  }

}

After we execute the above code, we will able to see the result that is given below:

10
java.lang.ArrayIndexOutOfBoundsException: 6

 

Leave a Reply