Thursday, September 11, 2014

Method Overriding with Exception Handling

Method Overriding with Exception Handling

There are many rules if we talk about method overriding with exception handling. The Rules are as follows:
  • If the super class method does not declare an exception
    • If the super class method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
  • If the super class method declares an exception
    • If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 
     
  1. If the super class method does not declare an exception 
    1. If the super class method does not declare an exception, subclass overridden method cannot declare the checked exception.
      import java.io.*;  
       class Parent{  
            void msg(){System.out.println("parent");}  
        }  
            
       class Child extends Parent{  
            void msg()throws IOException{  
              System.out.println("child");  
            }  
          public static void main(String args[]){  
             Parent p=new Child();  
             p.msg();  
          }  
        } 
      Output:Compile Time Error 
    2. If the super class method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.
      import java.io.*;  
      class Parent{  
        void msg(){System.out.println("parent");}  
      }  
        
      class Child extends Parent{  
        void msg()throws ArithmeticException{  
          System.out.println("child");  
        }  
        public static void main(String args[]){  
         Parent p=new Child();  
         p.msg();  
        }  
      }  
      Output:child
  2. If the super class method declares an exception
    1. If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.
          import java.io.*;  
          class Parent{  
            void msg()throws ArithmeticException{System.out.println("parent");}  
          }  
            
          class Child extends Parent{  
            void msg()throws Exception{System.out.println("child");}  
            
            public static void main(String args[]){  
             Parent p=new Child();  
             try{  
             p.msg();  
             }catch(Exception e){}  
            }  
          } 
      Output:Compile Time Error 
      

1 comment:

Tha 𝗔𝗣𝗜 Design 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸

 Here is the 𝟮𝟬𝟮𝟲 𝗔𝗣𝗜 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸 broken down by architecture: 𝟭. 𝗧𝗵𝗲 "𝗥𝗲𝗾𝘂𝗲𝘀𝘁-𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗲" 𝗧𝗿𝗶𝗼: ...