I have some code that throws a checked exception. I want to call that code within a lambda in order to create a map from another map:
Map<String, Coordinate> map = getMap();
Map<String, Integer> result = map.entrySet().stream().collect(
toMap(x -> x.getKey(), x -> doSomething(x.getValue)));
where doSometing
is the code that throws the exception:
int doSomething(Coordinate c) throws MyException { ... }
Now compiler surely complains about the exception not being handled. So I surround it with a try-catch
, which looks pretty ugly:
Map<String, Integer> result = map.entrySet().stream().collect(
toMap(x -> x.getKey(), x -> {
try {
return doSomething(x.getValue());
} catch (MyException e) {
e.printStackTrace();
// return some error-code here???
}
}));
which also does not compile as we need to return something in the catch
-case. However there´s not much sense in returning anything here in this exceptional case, which is why I actually do not want to handle the exception at that level. Can´t I just handle the exception in my calling code, where I create the lambda? So to say just one level above?
try {
Map<String, Integer> result = ...
} catch (MyException e) { ... }
But that does not compile because the exception thrown from the lambda is not handled.