Saturday, 16 August 2014

Exception Handling with Multiple Catch Blocks


When a single try block throws multiple exception in the same hierarchy, in this case we can handle those exception with catch having Exception class only. But it is not a good idea and it's not a perfect way to handle exception. The perfect way is to maintain the hierarchy of exceptions. When ever you are required to perform such operation, first of all handle with the sub-class and then super-class and then more super-class of exceptions.

Following code snippet displays the same with three small demos.

public static void main(String[] args) {

  //demo 1 with fileNotfoundException.
File f=new File("abc.txt");
try {
FileReader fr=new FileReader(f);

} catch (FileNotFoundException fnfe) {
System.out.println("FileNotFoundException : "+fnfe);

}catch(IOException ioe){
System.out.println("IOException : "+ioe);

}catch (Exception e) {
System.out.println("Exception : "+e);
              }


    // demo 2 with ArrayIndexOutOfBoundsException.
try{
String [] strArr={"one","two","three","four"};
System.out.println(strArr[4]);

}catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException : "+e);

}catch (IndexOutOfBoundsException ebe) {
System.out.println("IndexOutOfBoundsException : "+ebe);

}catch (Exception e) {
System.out.println("Exception : "+e);
}

 
 // demo 3 with StringIndexOutOfBoundsException.
try{
String str="one";
System.out.println(str.substring(4));

}catch(StringIndexOutOfBoundsException sibe){
System.out.println("StringIndexOutOfBoundsException : "+sibe);

}catch (IndexOutOfBoundsException ebe) {
System.out.println("IndexOutOfBoundsException : "+ebe);

}catch (Exception e) {
System.out.println("Exception : "+e);

}
   }

Output:


No comments:

Post a Comment