Java 8 handling custom exceptions when using Collectors.toMap

Is there any support for handling custom exceptions inside Collectors.toMap. I call a method inside Collector.toMap that throws MyException. Can it be restored in the pupulateValues ​​() calling function ? To demonstrate, I used the code below to recover MyException, but could not get through. My goal is to handle MyException in the main method.

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
source share
1 answer

You have several options:

+6

Source: https://habr.com/ru/post/1687344/


All Articles