Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

exception

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 constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor"

This is when having to throw exceptions to FileReader and BufferedReader.

Thanks

EDIT:

FileReader textFilethree = new FileReader (xFile);
BufferedReader bufferedTextthree = new BufferedReader (textFilethree) ;
String lineThree = bufferedTextthree.readLine();

The xFile is gotten from the construction. Note that within this construction exceptions are thrown.

like image 982
Ian Avatar asked Jul 21 '11 07:07

Ian


2 Answers

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
  }
}
like image 153
jmj Avatar answered Sep 30 '22 10:09

jmj


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]

like image 43
iammilind Avatar answered Sep 30 '22 12:09

iammilind