Subclassing from classes with Java constructors throwing exceptions

advertisements

My understanding is that overriding method in subclass should throw no exception or narrower exception from that on base method of parent class. Why does it work the opposite in constructors, the constructor of subclass has to throw the same exception or wider, Any reasonable explanation for this?

class MyException extends Exception{}
class MySubException extends MyException{}
class MySubSubException extends MySubException{}

public class Alpha {

  public Alpha() throws MyException{

  }
  void foo() throws MyException {}
}

class Beta extends Alpha{

 public Beta() throws MyException{ //NOT MySubSubException
    super();
 }

 void foo() throws MySubException {} //Ok for methods
}


Why does it work the opposite in constructors, the constructor of subclass has to throw the same exception or wider, Any reasonable explanation for this?

A subclass constructor always invokes its parent constructor with a call to super(..). In this case, the parent constructor is declared as throwing a checked exception of type MyException. Your subclass constructor must be able to handle that (with a throws since super(..) has to be the first statement in the constructor body).

With methods, you're not forced to invoke the super implementation.