2017-03-21 67 views
-1

爲什麼下面的代碼片段java的「拋出」的條款不工作

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

一類導致線路throw new VersionNotFoundException();提出一個編譯器錯誤VersionNotFoundExceptionmust be caught or declared to be thrown?它非常清楚地被宣佈爲被拋出。

+1

你應該定義會因lambda函數 –

+0

,你也應該遵循Java命名約定。 –

+0

@LewBloch你能詳細說明一下嗎?我見過的大多數java命名約定都會考慮這種兼容性。 –

回答

1

您重寫的lambda方法在其簽名中沒有VersionNotFoundException,因此重寫的方法不能(包括您的lambda)。由於#forEach接受不允許檢查異常的使用者,因此您總是必須捕獲該lambda中的異常。

至於確定是否需要拋出一個異常,我會做#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()的lambda函數沒有throws。這就是錯誤所說的。

0

檢查異常無法在lambda表達式中拋出。這是在lambda內的事實滑倒了我的腦海。

+0

那麼他們可以,接收方法必須接受一個允許檢查異常的功能接口 – Rogue

+0

@Rogue我已經找到了一個stackoverflow答案我說這是不能做到的。那從那以後改變了嗎? http://stackoverflow.com/a/27668305/4160312 –

+0

您可以指定自己的功能接口,並將其用於方法。然而,這並不是完全兼容流式的 – Rogue