How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?
In other words, I want to make code like this compile:
public List
I use this kind of wrapping exception:
public class CheckedExceptionWrapper extends RuntimeException {
...
public CheckedExceptionWrapper rethrow() throws T {
throw (T) getCause();
}
}
It will require handling these exceptions statically:
void method() throws IOException, ServletException {
try {
list.stream().forEach(object -> {
...
throw new CheckedExceptionWrapper(e);
...
});
} catch (CheckedExceptionWrapper e){
e.rethrow();
e.rethrow();
}
}
Try it online!
Though exception will be anyway re-thrown during first rethrow()
call (oh, Java generics...), this way allows to get a strict statical definition of possible exceptions (requires to declare them in throws
). And no instanceof
or something is needed.