4

Is there any support for handling custom exception inside the Collectors.toMap. I am calling a method inside the Collector.toMap which throws MyException. Can it be rethrown in the calling function pupulateValues()? For demonstration I used below code to rethrow MyException but couldn't get through. My objective is to handle MyException in 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;
}
Madhu CM
  • 2,296
  • 6
  • 29
  • 38

1 Answers1

6

You have a few options:

  1. make MyException an unchecked exception
  2. wrap it: catch (MyException e) { throw new RuntimeException(e); }
  3. trick the compiler:
assylias
  • 321,522
  • 82
  • 660
  • 783