Saturday, 22 February 2014

Catch block

catch block handles the exceptions that are thrown inside the try block. Each try block has more than one catch blocks associated with it.

Syntax
    try {

   
    catch (ExceptionType name) {

    }
     catch (ExceptionType name) {

    }

Each catch block handles the type of exception indicated by its argument.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(ArithmeticException e){
   System.out.println("inside Arithmetic Exception " + e);
  }
  catch(Exception e){
   System.out.println("inside Exception " + e);
  }
 }
}
   

Output
inside Arithmetic Exception java.lang.ArithmeticException: / by zero

Both handlers print an error message, but the program throwing ArithmeticException, so the code in the first handler executed and other not.

Some points to remember
1. While handling the exceptions, always handles the subclass exceptions first, next the super class.I.e, handle the ArithmeticException first, next Exception. Since ArithmeticExceptin is a subclass of Exception class. Other wise compiler throws error.

Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(Exception e){
   System.out.println("inside IOException " + e);
  }
  catch(ArithmeticException e){
   System.out.println("inside Airthmetic Exception " + e);
  }
 }
}
       
When you tries to compile the above program, compiler throws the below error
 
ExceptionEx.java:11: error: exception ArithmeticException has already been caught
    catch(ArithmeticException e){
    ^
    1 error

2. A catch can contain try inside.
Example
class ExceptionEx{
 public static void main(String args[]){
  try{
   System.out.println(10/0);
  }
  catch(Exception e){
   try{
   }
   catch(Exception e1){
   }
  }
 }
}
  



try                                                 Catching multiple exceptions                                                 Home

No comments:

Post a Comment