0

So I use the line a lot.

FileReader reader = new FileReader(file)

and I want to make this line a member variable. Like this:

private FileReader reader = new FileReader(file);

The problem is that java doesn't like this and gives the error:

The default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor Java(16777362)

So I made a constructor like this:

protected Json() throws FileNotFoundException
{
    //
}

the problem is, is that I use the JSON class in different classes and those classes will give the same error, so I had to edit the other classes, but that ended up looking really ugly and gave a lot of problems. Is there a solution to this problem?

Nope 69
  • 51
  • 5
  • Did you consider to handle (try/catch) the exception sooner? Or is that not feasible? – MDK Oct 20 '20 at 08:47
  • Also take a look at [this](https://stackoverflow.com/questions/9354791/java-error-default-constructor-cannot-handle-exception-type-filenotfound-except), [this](https://stackoverflow.com/questions/28854207/default-constructor-cannot-handle-exception-type-ioexception-thrown-by-implicit) or [this](https://stackoverflow.com/questions/6772709/while-constructing-the-default-constructor-can-not-handle-exception-type-excep), all of which discuss the same problem – MDK Oct 20 '20 at 08:49
  • use an aggregation instead on a composition https://stackoverflow.com/a/1468285/8030651 ➡️ you can localize problem with `FileReader ` initialization – kozmo Oct 20 '20 at 08:52

1 Answers1

0

So I decided to do it like this

JSONArray jsonArray = (JSONArray) jsonParser.parse(new FileReader(file));
Nope 69
  • 51
  • 5