Java:捕获lambda异常

Java:捕获lambda异常,java,lambda,java-8,Java,Lambda,Java 8,无法在try/catch块中包装流对象 我试着这样做: reponseNodes.stream().parallel().collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> processImage(responseNode))); Eclipse开始抱怨在processImage(responseNode)下面加下划线,并建议它需要用try/catch围绕 然后我更新到

无法在
try/catch块中包装流对象

我试着这样做:

reponseNodes.stream().parallel().collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> processImage(responseNode)));
Eclipse开始抱怨在
processImage(responseNode)
下面加下划线,并建议它需要
用try/catch围绕

然后我更新到:

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

更新的代码也不起作用。

在lambadas中没有直接的方法来处理选中的异常,我提出的唯一选择就是将逻辑移到另一个方法,该方法可以通过try-catch处理它

比如说,

List fr=Arrays.asList(“a.txt”、“b.txt”、“c.txt”).stream()
.map(a->createFileReader(a)).collect(Collectors.toList());
//....
私有静态文件读取器createFileReader(字符串文件){
FileReader fr=null;
试一试{
fr=新文件读取器(文件);
}catch(filenotfounde异常){
e、 printStackTrace();
}
返回fr;
}

在lambadas中没有直接的方法来处理选中的异常,我提出的唯一选择就是将逻辑移到另一个方法,该方法可以通过try-catch来处理它

比如说,

List fr=Arrays.asList(“a.txt”、“b.txt”、“c.txt”).stream()
.map(a->createFileReader(a)).collect(Collectors.toList());
//....
私有静态文件读取器createFileReader(字符串文件){
FileReader fr=null;
试一试{
fr=新文件读取器(文件);
}catch(filenotfounde异常){
e、 printStackTrace();
}
返回fr;
}

因为lambda不再是单个语句,所以每个语句(包括
processImage(responseNode)
后面必须跟一个
。出于同样的原因,lambda还需要一个显式的return语句(
returnprocessimage(responseNode)
),并且必须用
{}
包装

因此:


因为lambda不再是单个语句,所以每个语句(包括
processImage(responseNode)
后面必须跟一个
。出于同样的原因,lambda还需要一个显式的返回语句(
returnprocessimage(responseNode)
),并且必须用
{}
包装

因此:


你能键入Eclipse给你的确切警告/错误吗?Eclipse警告
用try/catch包围
下划线
processImage(responseNode)
。你能键入Eclipse给你的确切警告/错误吗?Eclipse警告
用try/catch包围
下划线
processImage(responseNode)
。这可能是最好的。这更具可读性。>lambadas最佳打字法可能是最好的。这更具可读性。>lambadas最佳打字法
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;
}
return reponseNodes.stream().parallel()
        .collect(Collectors.toMap(responseNode -> responseNode.getLabel(), responseNode -> {
            try {
                return processImage(responseNode);
            } catch (Exception e) {
                throw new UncheckedException(e);
            }
        }));