blog

Home / DeveloperSection / Blogs / Multiple catch block in java

Multiple catch block in java

Anonymous User3252 23-May-2015

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.

staticvoid main(string … args)
{
try
{
int a[] = newint[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 .

staticvoid main(string … args)
{
try
{
int[] a = newint[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


Updated 26-Feb-2018
I am a content writter !

Leave Comment

Comments

Liked By