4
是否支持在Collectors.toMap内处理自定义异常。 我在调用MyException的Collector.toMap内调用一个方法。是否可以在调用函数pupulateValues()?中重新生成?为了演示,我使用下面的代码重新引发MyException,但无法通过。我的目标是在main方法中处理MyException。java 8处理使用Collectors.toMap时的自定义异常
public static void main(String[] args){
try {
pupulateValues();
} catch (MyException e) {
// do something
e.printStackTrace();
}
}
private static void pupulateValues() throws MyException{
Map<String,String> map = new HashMap<>();
map.put("asdf", "asdf");
map.put("ss", "fff");
map.put("aaaaaa", "aaaaaaa");
Map<String,String> map2=map.entrySet().stream().collect(
Collectors.toMap(entry->entry.getKey(),entry-> {
try {
return getCert(entry.getValue());
} catch (MyException e) {
// TODO Auto-generated catch block
throw new MyException();
}}));
}
static String getCert(String val) throws MyException {
if(val == null) {
throw new MyException("Some exception");
}
return val;
}
4.使用 –