【问题标题】:Java: Catching lambda exceptions [duplicate]Java:捕获 lambda 异常
【发布时间】:2016-03-10 22:30:31
【问题描述】:

无法将流对象包装在 try/catch block 中。

我试过这样:

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); }));

更新的代码也不起作用。

【问题讨论】:

  • 您能输入 Eclipse 给您的确切警告/错误吗?
  • Eclipse 警告Surround with try/catch 下划线processImage(responseNode)

标签: java lambda java-8


【解决方案1】:

因为 lambda 不再是单个语句,所以每个语句(包括processImage(responseNode) 后面必须跟一个;。同理,lambda 也需要显式返回语句(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);
            }
        }));

【讨论】:

    【解决方案2】:

    没有直接的方法来处理lambdas中的已检查异常,我想出的唯一选择是将逻辑移动到另一个可以使用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;
    }
    

    【讨论】:

    • 这可能是最好的。这更具可读性。
    • >lambadas 有史以来最好的错字
    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多