Saturday, 22 February 2014

Catching More Than One Exception with One Handler

Prior to Java7 one catch block able to handle one type of Exception. In java 7, a single catch block can handle more than one type of exception.

Syntax
    catch(ExceptionType1 | ExceptionType2 e ){

    }

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }

  catch(ArithmeticException | ArrayIndexOutOfBoundsException e){
   System.out.println(e);
  }
 }
}
 
Output
java.lang.ArithmeticException: / by zero

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter “e” is final.

Some points to Remember
1. Trying to handle same type(subclass and super class like) of Exceptions in the catch block throws compiler error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }

  catch(ArithmeticException | Exception e){
   System.out.println(e);
  }
 }
}
  
Since ArithmeticException is a sub class of Exception class, so when you tries to compile the above program, compiler throws the below error.

ExceptionEx.java:7: error: Alternatives in a multi-catch statement cannot be related by subclassing
catch(ArithmeticException | Exception e){
^
Alternative ArithmeticException is a subclass of alternative Exception
1 error

catch block                                                 finally block                                                 Home

No comments:

Post a Comment