Monday 16 May 2016

Why can't overriding methods throw exceptions broader than the overriden method?

It means that if a method declares to throw a given exception, the overriding method in a subclass can only declare to throw that exception or its subclass (equal or lower in hierarchy or no exception).

class ParentClass {
      public void method1() throws IOException {

      }

      public void method2() throws SQLException {

      }
}

class BaseClass extends ParentClass {
      @Override
      public void method1() throws SocketException {
           
      }//Allowed: SocketException extends IOException i.e lower in hierarchy

      @Override
      public void method2() throws Exception {

      }//NOT allowed: Exception is parent to SQLException Higher in hierarchy
}


Reason to not throw the exception of higher hierarchy in java

This is because of runtime polymorphism.

public class TestException {

      public static void main(String[] args) {
            ParentClass p = new BaseClass();
           
            try {
                  p.method2();
            } catch (SQLException ex) {
                  // forced to catch this by the compiler
            }
      }
}

As given in above example, we are throwing the SQLException from method2() of ParentClass. At the compile time, we handled the SQLException because compiler doesn’t aware about Parent class reference will contain the instance of child class at runtime.

But due to runtime polymorphism, the method of base class of exception hierarchy and the catch block will not capable to handle this higher hierarchy Exception.

Therefore, throwing the exception of higher hierarchy is not allowed in java.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...