Home > DeveloperSection > Blogs > Multiple catch block in java

Multiple catch block in java


Exception Handling Java  Exception 
Ratings:
1 Comment(s)
 660  View(s)
Rate this:

Multiple catch block in java

Hi everyone in this blog I’m explaining about multi catch block of 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 occured 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


Exception handling

By Mayank Tripathi on   one year ago
Check more posts on exceptions handling here

Don't want to miss updates? Please click the below button!

Follow MindStick