Tuesday, 19 August 2014

Exception Throwing Handling with Method Overriding


Exception handling is the process of handling exception raised by a block of code. We can handle exception by using try catch block or it can be thrown to the calling method.

Now the question is How to throws exception in case of method overriding? 

In case of method overriding, overriding method always throws same exception or sub-class of what overridden method is throwing. Throwing exception is always remain same or downgraded in case of overriding. Following snippet of code demonstrates it deeply.

package javawrapper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

//Used as SuperClass.
class Super1Class{

//Throwing IOException.
void printFile() throws IOException
{

}

//Throwing IndexOutOfBoundsException
protected void readArrayElements() throws IndexOutOfBoundsException
{

}

//Throwing StringIndexOutOfBoundsException
public void throwSameException() throws StringIndexOutOfBoundsException
{

}
}


//Sub-class of Super1Class.
public class ExceptionHandlingWithOverriding extends Super1Class {

    //overriding method printFile throwing exception sub-class of, what overridden method is throwing.
protected void printFile() throws FileNotFoundException
{
File file=new File("file.txt");
FileReader fr=new FileReader(file);
}

//overriding method readArrayElements throwing exception sub-class of, what overridden method is throwing.
public void readArrayElements() throws ArrayIndexOutOfBoundsException
{
Integer [] intArr={1,2,3,4,5};
System.out.println(intArr[5]);
}

   //overriding method throwSameException throwing same exception as overridden method is throwing.
public void throwSameException() throws StringIndexOutOfBoundsException
{

}

   public static void main(String[] args) {

  ExceptionHandlingWithOverriding objExpHand=new ExceptionHandlingWithOverriding();
  
  // Handling FileNotFoundException.
  try {
objExpHand.printFile();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException : "+e+" \n");
}
  
  //Handling ArrayIndexOutOfBoundsException.
  try {
  objExpHand.readArrayElements();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException : "+e);
}
 
          // Calling throwSameException method.
  objExpHand.throwSameException();
  
}

}

Output:









No comments:

Post a Comment