-1

Why does the following code snippet

private void getEvents() throws VersionNotFoundException{
    gameRepository.findAll().forEach(game->{
        HttpHeaders headers = new HttpHeaders();
        String appVersion = getClass().getPackage().getImplementationVersion();
        if (appVersion==null) {
            throw new VersionNotFoundException();
        }
        headers.set("X-TBA-App-Id","4205:"+this.getClass().getPackage().getImplementationVersion());
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);
        restTemplate.exchange(getEventsForYearString, HttpMethod.GET,requestEntity , Event.class, game.getYear());
    });
}

private class VersionNotFoundException extends Exception {
}

in a class cause the line throw new VersionNotFoundException(); to raise a compiler error that VersionNotFoundException must be caught or declared to be thrown? It very clearly is declared to be thrown.

Trevor Giddings
  • 387
  • 1
  • 4
  • 17

3 Answers3

3

The lambda function passed to gameRepository.findAll().forEach() doesn't have throws. That's what the error is saying.

kaitoy
  • 1,545
  • 9
  • 16
1

the lambda method you're overriding doesn't have VersionNotFoundException in its signature, so overridden methods can't either (including your lambda). Since #forEach accepts a consumer which doesn't allow checked exceptions, you always have to catch exceptions in that lambda.

As for determining if you need to throw an exception, I would do that outside of the #forEach entirely:

private void getEvents() throws VersionNotFoundException {
    String appVersion = getClass().getPackage().getImplementationVersion();
    if (appVersion == null) {
        throw new VersionNotFoundException();
    }
    gameRepository.findAll().forEach(game-> {
        HttpHeaders headers = new HttpHeaders();
        headers.set("X-TBA-App-Id", "4205:"+ appVersion);
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);
        restTemplate.exchange(getEventsForYearString, HttpMethod.GET, requestEntity, Event.class, game.getYear());
    });
}
Rogue
  • 11,105
  • 5
  • 45
  • 71
0

Checked Exceptions cannot be thrown in lambda expressions. The fact that this was inside a lambda slipped my mind.

Trevor Giddings
  • 387
  • 1
  • 4
  • 17
  • Well they can, the receiving method has to accept a functional interface which allows a checked exception – Rogue Mar 21 '17 at 05:41
  • @Rogue I had found a stackoverflow answer I that said It couldn't be done. Has that changed since then? http://stackoverflow.com/a/27668305/4160312 – Trevor Giddings Mar 21 '17 at 06:21
  • You can specify your own functional interfaces, and utilize those for methods. However this isn't wholly stream-compatible – Rogue Mar 21 '17 at 07:16