Object Oriented Programming: Unit III: Exception Handling and Multithreading

Multiple Catch Clauses

with Example Exception Handling Java Programs

It is not possible for the try block to throw a single exception always.There may be the situations in which different exceptions may get raised by a single try block statements and depending upon the type of exception thrown it must be caught.

Multiple catch Clauses

• It is not possible for the try block to throw a single exception always.

• There may be the situations in which different exceptions may get raised by a single try block statements and depending upon the type of exception thrown it must be caught.

• To handle such situation multiple catch blocks may exist for the single try block statements.

• The syntax for single try and multiple catch is -

try

{

...//exception occurs

}

catch(Exception_type e)

{

...//exception is handled here

}

catch (Exception_type e)

{

...//exception is handled here

}

catch(Exception_type e)

{

...//exception is handled here

}

Example

Java Program[MultipleCatchDemo.java]

class MultipleCatchDemo

{

public static void main(String args[])

{

int all = new int [3];

try

{

for (int i = 1; i <=3; i++)

{

a[i] = i *i;

}

for (int i = 0; i <3; i++)

{

a[i] = i/i;

}

}

catch (ArrayIndexOutOfBoundsException e)

{

System.out.println ("Array index is out of bounds");

}

catch (ArithmeticException e)

{

System.out.println ("Divide by zero error");

}

}

}

Output

Array index is out of bounds

Note: If we comment the first for loop in the try block and then execute the above code we will get following output

Divide by zero error

Object Oriented Programming: Unit III: Exception Handling and Multithreading : Tag: : with Example Exception Handling Java Programs - Multiple Catch Clauses