2015-12-06 152 views
1

無法在try/catch block中包裝流對象。Java:捕捉lambda異常

我想是這樣的:

reponseNodes.stream().parallel().collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> processImage(responseNode))); 

啓動Eclipse抱怨強調processImage(responseNode)和建議,它需要Surround with try/catch

然後我更新爲:

return reponseNodes.stream().parallel().collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> try { processImage(responseNode) } catch (Exception e) { throw new UncheckedException(e); })); 

更新代碼也沒有工作。

+0

您可以輸入Eclipse提供給您的確切警告/錯誤嗎? –

+0

Eclipse警告'環繞着try/catch'強調'processImage(responseNode)'。 –

回答

2

沒有直接的方法來處理lambda中的檢查異常,只有我想出的選項只是將邏輯移動到另一個方法,可以用try-catch來處理它。

例如

List<FileReader> fr = Arrays.asList("a.txt", "b.txt", "c.txt").stream() 
      .map(a -> createFileReader(a)).collect(Collectors.toList()); 
//.... 
private static FileReader createFileReader(String file) { 
    FileReader fr = null; 
    try { 
     fr = new FileReader(file); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return fr; 
} 
+2

這可能是最好的。這更可讀。 –

+1

> lambadas有史以來最好的錯字 –

5

因爲拉姆達不再是一個單獨的語句,每個語句(包括processImage(responseNode)必須後跟一個;。出於同樣的原因,拉姆達也需要一個明確的回報聲明(return processImage(responseNode)),並且必須被包裹在{}

因此:

return reponseNodes.stream().parallel() 
     .collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> { 
      try { 
       return processImage(responseNode); 
      } catch (Exception e) { 
       throw new UncheckedException(e); 
      } 
     }));