Hi everyone in this blog I’m explaining about the multi-catch block of the single try block.

Introduction:

If you have to perform different tasks at the occurrence of different Exceptions, use java multi-catch block.

Let's see a simple example of java multi-catch block.

static void main(string … args)
{
try
{
int a[] = new int[5];
a[5] = 30/0 ;
System.out.println(a[5]);
}
catch(ArithmeticException ex)
{
System.out.println ("task1 is completed...");
}
catch (IndexOutOfBoundException ex)
{
System.out.println ("task2 is completed...");
}
catch (Exception ex)
{
System.out.println ("common task is completed...");
}
System.out.println("rest of the code...");
}

Output:

Task1 completed…

Rest of the code…


Rule 1: At a time only one exception is occurred and at a time only one catch block is executed.

Rule 2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .

static void main(string … args)
{
try
{
int[] a = new int[5];
a[5] = 30/0 ;
System.out.println(a[4]);
}
catch (Exception ex)
{
System.out.println("common task is completed...");
}
catch(ArithmeticException ex)
{
System.out.println("task1 is completed...");
}
catch (IndexOutOfBoundException ex)
{
System.out.println("task2 is completed...");
}
System.out.println("rest of the code...");
}

Output:

Compile time Error

  Modified On Feb-26-2018 01:07:16 AM

Leave Comment