spacing
spacing

Reputation: 780

Catching exception thrown by method inside method

So let's say I have a class App which is where I am doing error handling and on this particular class I do

   try {
        layermethod();
    } catch (IOException e) {
        Message.fileNotFound(filename);
    }

layermethod() is of the Layer class which is a "mask" class that I use to pass info from the App to the Core application and into objects.

So in the Class layer layermethod() is only defined as

 public void layermethod(Parser _parser) {
    _parser.throwmethod(_interpreter);
    }

And only in the Parser Class I do have the method that actually throws the exception

  public void throwmethod(Parser _parser) throws IOException {
        // method implementation
    }

Unfortunately as is, I get the error

error: unreported exception IOException; must be caught or declared to be thrown
        _parser.throwmethod(_parser);
                         ^

Because I'm not catching the exception on the layer class.

Is there any way I can only do the error handling (catch the exceptions) on the App class only? Assuming I can't ditch the layer class

Upvotes: 1

Views: 1980

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521249

You have two options. Either you can refactor Layer.layermethod() to also throw an IOException:

public void layermethod(Parser _parser) throws IOException {
    _parser.throwmethod(_interpreter);
}

or, you can explicitly add a try catch block in the above method:

public void layermethod(Parser _parser) {
    try {
        _parser.throwmethod(_interpreter);
    } catch (IOException e) {
        // handle exception here
    }
}

Given that you seem to want to bring the exceptions up into the App class, the former option is probably what you have in mind.

Upvotes: 1

Related Questions