Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Exceptions Handling Multiple Catch Clauses

 
 

Share on Google+Share on Google+

Handling Multiple Catch Clauses

Advertisement
So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.

Handling Multiple Catch Clauses

     

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.

The syntax for using this clause is given below:-

try{
???
???
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception  
}

catch(<exceptionclass_2> <obj2>){
//statements to handle the exception  
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception  
}

 

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level.

 

Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.

 

public class Multi_Catch
{
   public static void main (String args[])
   {
  int array[]={20,10,30};
  int num1=15,num2=0;
  int res=0;

  try
  {
   res = num1/num2;
  System.out.println("The result is" +res);

  for(int ct =2;ct >=0; ct--)
  {
   System.out.println("The value of array are" +array[ct]);
   }

  }

  catch (ArrayIndexOutOfBoundsException e)
   {
   System.out.println("Error?. Array is out of Bounds");
  }

   catch (ArithmeticException e) 
   { 
   System.out.println ("Can't be divided by Zero"); 
   }

  }
  }

 

 

Output of the program:

 
C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Can't be divided by Zero

In this example we have used two catch clause catching the exception ArrayIndexOutOfBoundsException and ArithmeticException in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time  the first catch block is skipped and the second catch block handles the error.

Download this program

Lets have an another output, in which the second catch block is skipped and the first catch block handles the error.

public class Multi_Catch1
{
   public static void main (String args[])
   {
  int array[]=new int [5];
  int num1=15,num2=2;
  int res=0;

  try
  {
   res = num1/num2;
  System.out.println("The result is" +res);

  for(int ct =0;ct <=5; ct++)
  {
   array[ct] = ct * ct ;
   }

  }

  catch (ArrayIndexOutOfBoundsException e)
   {
   System.out.println("Assigning the array beyond the upper bound");
  }

   catch (ArithmeticException e) 
   { 
   System.out.println ("Can't be divided by Zero"); 
   }

  }
  }

 

 

Output of the program:

 
C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Assigning the array beyond the upper bound

Download this example

Handling the Unreachable Code Problem 

The multiple catch blocks can generate unreachable code error i.e. if the first catch block contains the Exception class object then the subsequent catch blocks are never executed.  This is known as Unreachable code problem. To avoid this, the last catch block in multiple catch blocks must contain the generic class object that is called the Exception class. This exception class being the super class of all the exception classes and is capable of  catching any  types of exception. The generic Exception class can also be used with multiple catch blocks.

Take a look at the following example:

public class Generic_Excep
{
   public static void main (String args[])
  { 
   String str = "Exception" ;
   int len=0;
   try
  {
   StringBuffer sbuf = new StringBuffer(str);
  len = str.length() ;
   for(int ct=len;ct>=0;ct--)
  {
  System.out.print(sbuf.charAt(ct));
   }
   }
   catch(Exception e)
  {
  System.out.println("Error...."+e);
   }
   }
   }

 

Output of the program:

C:\Roseindia\>javac Generic_Excep.java

C:\Roseindia\>java Generic_Excep

Error....java.lang.StringIndexOutOfBoundsException: String index out of range: 9

In this example we didn't specify that which one exception may occur during the execution of program but here we are trying to access the value of an array that is out of bound still we don't need to worry about handle the exception because we have used the Exception class that is responsible to handle any type of exception.

Download this example

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 11, 2009

Related Tutorials

Discuss: Handling Multiple Catch Clauses   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com