1

I am trying to throw an exception inside lambda but it keeps giving me an error saying that Unhandled IOException.

 private  <T> T getResponse(final RestURI query, final Class<T> responseClass) throws IOException {
        return getValue(query,
            reader -> {
                try {
                    return mapper.readValue(reader, responseClass);
                } catch (IOException e) {
                    throw new IOException("Exception while deserializing the output " + e.getMessage());
                }
        });
}

Can someone tell me what I am doing wrong ?

user3407267
  • 1,524
  • 9
  • 30
  • 57
  • 2
    In any case, don't rethrow like this: provide `e` as a cause to the new exception (if you actually need that at all), in order to provide the stack trace of the actual exception. – Andy Turner Aug 24 '18 at 20:03

1 Answers1

2

The functional interface you use in getValue() doesn't specify the IOException checked exception in this signature.
So you cannot throw it as only declared checked exceptions may be thrown inside the lambda body.
Either create and use your own functional interface that declares IOException or instead throw any RuntimeException instance from the lambda, which is valid.
For example UncheckedIOException as suggested by MC Emperor.

Besides you should throw the new exception by chaining it to the cause exception to keep the information in the stracktrace:

try {
    return mapper.readValue(reader, responseClass);
} catch (IOException e) {
    throw new UncheckedIOException("Exception while deserializing the output ", e);
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 2
    Or throw an `UncheckedIOException`. – MC Emperor Aug 24 '18 at 20:25
  • Good answer, however it's best that junior developer learn not to default to throwing `RuntimeException` everywhere because it lacks clarity. You should extend RuntimeException and call it something like `JsonParseException` in this case. @MCEmperor also gives an elegant solution if you don't want to create your own class. However prefer domain specific classes. – Brad Aug 24 '18 at 20:56
  • @Brad Completely agree about typing. But `JsonParseException` exists already in Jackson. In fact the OP wants to re-throw any exception thrown by `ObjectMapper.readValue()` that actually throw multiple flavors of `IOException` : ` IOException, JsonParseException, JsonMappingException`. So the MC Emperor is probably a good hint for this usecase. – davidxxx Aug 24 '18 at 21:09
  • @MC Emperor very good hint. – davidxxx Aug 24 '18 at 21:10