Java Exception Handling with Method Overriding


There are many rules if we talk about methodoverriding with exception handling. The Rules are as follows:

If the superclass method does not declare an exception

If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.

If the superclass method declares an exception

If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.


Example of Subclass overriden Method declaring Checked Exception

import java.io.*;
class Super
{
 void show() { System.out.println("parent class"); }
}

public class Sub extends Super 
{
 void show() throws IOException		 
  { System.out.println("parent class"); } 

 public static void main( String[] args )
 {
  Super s=new Sub();
  s.show();
 }  
}
Output
Compile time error

Example of Subclass overriden Method declaring Unchecked Exception

import java.io.*;
class Super
{
 void show(){ System.out.println("parent class"); }
}

public class Sub extends Super 
{
 void show() throws ArrayIndexOutOfBoundsException      
   { 
    System.out.println("child class"); 
    }

 public static void main(String[] args)
 {
  Super s=new Sub();
  s.show();
 }  
}
Output
child class

Example of Subclass overriden method with same Exception

import java.io.*;
class Super
{
 void show() throws Exception 
  {  System.out.println("parent class");  }
}

public class Sub extends Super {
 void show() throws Exception		  	  
   { System.out.println("child class"); } 

 public static void main(String[] args)
 {
  try {
   Super s=new Sub();
   s.show();
   }
  catch(Exception e){}
 }  
}
Output
child class

Example of Subclass overriden method with no Exception

import java.io.*;
class Super
{
 void show() throws Exception 
  {  System.out.println("parent class");  }
}

public class Sub extends Super {
 void show()             		 	  
   { System.out.println("child class"); } 

 public static void main(String[] args)
 {
  try {
   Super s=new Sub();
   s.show();
   }
  catch(Exception e){}
 }  
}
Output
child class

Example of Subclass overriden method with parent Exception

import java.io.*;
class Super
{
 void show() throws ArithmeticException 
  {  System.out.println("parent class");  }
}

public class Sub extends Super {
 void show() throws Exception         		 	  
   { System.out.println("child class"); } 

 public static void main(String[] args)
 {
  try {
   Super s=new Sub();
   s.show();
   }
  catch(Exception e){}
 }  
}
Output
Compile time Error

Share this article on