1

Not able to wrap stream object in a try/catch block.

I tried like this:

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

Eclipse started complaining underlining processImage(responseNode) and suggested that it needs to Surround with try/catch.

Then I updated to:

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

Updated code also did not work.

Himanshu Yadav
  • 13,315
  • 46
  • 162
  • 291

2 Answers2

5

Because the lambda is no longer a single statement, each statement (including processImage(responseNode) must be followed by a ;. For the same reason, the lambda also requires an explicit return statement (return processImage(responseNode)), and must be wrapped in {}.

Thus:

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

There is no direct way to handle checked exceptions in lambadas, only option I came up with is just move the logic to another method which can handle it with try-catch.

For example,

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;
}
akash
  • 22,664
  • 11
  • 59
  • 87