While constructing the default constructor can not handle exception : type Exception thrown by implicit super constructor

后端 未结 4 549
独厮守ぢ
独厮守ぢ 2020-11-29 10:19

The code works fine until I try to make the code into a constructable class. When I attempt to construct an object from it I get the error

\"Default

相关标签:
4条回答
  • 2020-11-29 10:54

    Just enclose your call to the Constructor in a Try-Catch.

    0 讨论(0)
  • 2020-11-29 10:55

    Default constructor implicitly invokes super constructor which is assumed to be throwing some exception which you need to handle in sub class's constructor . for detailed answer post the code

    class Base{
    
      public Base() throw SomeException{
        //some code
      }
    
    }
    
    class Child extends Base{
      public Child(){
       //here it implicitly invokes `Base()`, So handle it here
      }
    }
    
    0 讨论(0)
  • 2020-11-29 11:01

    Any subclass which extends a super class whose default constructor handles some exception, a subclass must have a default constructor which implements the exception

    class Super{ public Super() throws Exception {}}

    class Sub extends Super{public Sub()throws Exception{//}}

    0 讨论(0)
  • 2020-11-29 11:04

    Base class super.constructor is implicitly invoked by the extending class constructor:

    class Base
    {
      public Base () throws Exception
      {
        throw <>;
      }
    }
    
    class Derived extends Base
    {
      public Derived ()
      {
      }
    }
    

    Now, one need to handle the exception inside Derived() or make the constructor as,

    public Derived() throws Exception
    {
    }
    

    Whatever method you new up the object of Derived, either you enclose it in try-catch or make that method throwing Exception as above. [Note: this is pseudo code]

    0 讨论(0)
提交回复
热议问题