Subclasses of classes with Java constructors throwing exceptions

I understand that an overriding method in a subclass should not throw an exception or a narrower exception from the method of the base class of the parent class. Why does it work the opposite in constructors, should the subclass constructor 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
}
+4
source share
3 answers

Why is this the opposite in constructors, should a constructor subclass throw the same exception or wider, any reasonable explanation for this?

super(..). MyException. ( throws, super(..) ).

super.

+5

. - , , , . , , ; .

:

class A { 
    A f() throws MyException { ... }
}
class B {
    @Override
    B f() throws MySubException { ... }
}
class C {
    void g(A a) {
        ...
    }
}

f B f A, . B A, B.f A , , MyException. , B , A, g(A a) C.

. -, , ​​ , . ( ) . , try-catch, .

+1

Note @Hoopje, you cannot catch an exception in try {} catch when calling the superclass constructor with super (), you also need to declare throws in the subclass constructor.

0
source

All Articles