【问题标题】:java 8 handling custom exception when using Collectors.toMapjava 8 使用 Collectors.toMap 时处理自定义异常
【发布时间】:2017-10-12 13:00:12
【问题描述】:

是否支持在 Collectors.toMap 中处理自定义异常。 我在 Collector.toMap 中调用一个引发 MyException 的方法。可以在调用函数pupulateValues()中重新抛出吗?为了演示,我使用下面的代码重新抛出 MyException 但无法通过。我的目标是在 main 方法中处理 MyException。

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

【问题讨论】:

    标签: java java-8 java-stream


    【解决方案1】:

    你有几个选择:

    1. 使MyException 成为未经检查的异常
    2. 包装它:catch (MyException e) { throw new RuntimeException(e); }
    3. 欺骗编译器:

    【讨论】:

    • 4.使用 for 循环而不是流
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多