2017-03-21 1 views
-1

왜 다음 코드는 클래스에자바 절 라인 <code>throw new VersionNotFoundException();</code>이 <code>VersionNotFoundException</code><code>must be caught or declared to be thrown</code>하는 컴파일러 오류가 발생하는 원인

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 { 
} 

니펫 않습니다 작동하지 않는 "발생"? 그것은 매우 분명히 던져진 것으로 선언됩니다.

+1

는 람다 함수 –

+0

에 대한 던져 그리고 또한 자바 명명 규칙을 따라야합니다 : 당신이 예외를 던질 필요가 있다면, 나는 완전히 #forEach의 외부를 할 것입니다 결정으로

. –

+0

@LewBloch 자세히 설명해 주시겠습니까? 필자가 보아온 Java 명명 규칙의 대부분은이 규정을 준수한다고 생각합니다. –

답변

1

재정의하려는 람다 메서드의 서명에 VersionNotFoundException이 없으므로 재정의 된 메서드는 (람다 포함) 중 하나 일 수 없습니다. #forEach은 검사 된 예외를 허용하지 않는 소비자를 받아들이므로 항상 해당 람다에서 예외를 잡아야합니다.

당신은 정의해야
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()); 
    }); 
} 
+0

나는 foreach에서 일하고 있다는 것을 잊어 버렸습니다. 내가 알아 차린 후에, 나는 당신이 제안한 것보다 더 - 또는 - 적은 것으로 그것을 바 꾸었습니다. –

3

gameRepository.findAll().forEach()에게 전달 된 λ 함수에는 throws이 없습니다. 그것이 바로 오류입니다.

0

확인 된 예외는 람다 식에서 throw 될 수 없습니다. 이것이 람다 내부에 있다는 사실은 내 마음을 미끄러 뜨 렸습니다.

+0

잘 수있는 방법, 수신 방법은 확인 된 예외를 허용 기능적인 인터페이스를 받아 들일 수있다 – Rogue

+0

@ 로그 나는 그것을 할 수 없다고 stackoverflow 대답을 발견했다. 그 이후로 바뀌 었습니까? http://stackoverflow.com/a/27668305/4160312 –

+0

고유 한 기능 인터페이스를 지정하고 메소드에 사용할 수 있습니다. 그러나 이것은 전체 스트림 호환되지 않습니다 – Rogue

관련 문제