Powered by Blogger.

Multiple "catch" Clauses in JavaScript | Java

Introduction:-

The code bound by the try block need not always throw a single exception. If in a try block multiple and varied exceptions are thrown, then you can place multiple catch blocks for the same try block in order to handle all those exceptions. When an exception is thrown it traverses through the catch blocks one by one until a matching catch block is found. The program structure in such a case is:

Java Code:-

try
{
    // statements with multiple and varied exceptions
}
catch (<exception_one> obj)
{
    // statements to handle the exception
}
catch (<exception_two> obj)
{
    // statements to handle the exception
}
catch (<exception_three> obj)
{
    // statements to handle the exception
}

 Let us consider an example in which we are using two catch clauses catching the exception ArrayIndexOutOfBoundsException and ArithmeticException. In the first example a deliberate attempt has been made to store the value in the array beyond it’s upper limit thus causing the program to throw the exception ArrayIndexOutOfBoundsException, and to go to the first catch block. In the next example this error is rectified and the program is run again. A new error comes up which is the zero divide. Now this time the second catch block handles the error, and the first catch block is skipped.


Multiple Catch Clauses:-

In Java , there can be multiple catch blocks after a try block, and each catch block handing a different exception type.

Using Multiple catch Clauses Example:

 public class Multicatch{
   public static void main(String[]args){
     try{
        int i = 9/0;
        System.out.println(i);
     }catch(ArithmeticException e1){
        System.out.println(”Arithmetic Exception.” +e1);
     }catch(Exception e2){
        System.out.println(”Exception.” +e2);
     }
   }
 }

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

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 Array Index Out of Bounds Exception and Arithmetic Exception 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.

Like 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

Like 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.

Related Tags for Handling Multiple Catch Clauses:

java, c, exception,diff, io, multiple, type, ip, lock, block, handle, if, for, program, while, to, ram, run, single, exceptions, locks, generate, e, il, blocks, multi, can, use, ul, pe,  man, art, ce, in, part, different, m, nt, par, tr, clause, ca, j, cl, catch, running, icu, loc, how, pro, rate, cat, when, try, s, tip, at, any, k, ha, except, and, ar, rt, va, s, s, ren, th, av, hat, fe, many, ipl, ple, pl, pr, nd, only, on, ogr, o, nl

1 comment: