Suppose we try to apply to java 8 stream a lambda that could throw checked exception:
Stream<String> stream = Stream.of("1", "2", "3");
Writer writer = new FileWriter("example.txt");
stream.forEach(s -> writer.append(s)); // Unhandled exception: java.io.IOException
This won't compile.
One workaround is to nest checked exception in RuntimeException
but it complicates later exception handling and it's just ugly:
stream.forEach(s -> {
try {
writer.append(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
Alternative workaround could be to convert limited functional forEach
to plain old foreach loop that is more friendly to checked exceptions.
But naive approaches fail:
for (String s : stream) { // for-each not applicable to expression type 'java.util.stream.Stream<java.lang.String>'
writer.append(s);
}
for (String s : stream.iterator()) { // foreach not applicable to type 'java.util.Iterator<java.lang.String>'
writer.append(s);
}
Update
A trick that answers this question was previosly posted at Why does Stream<T> not implement Iterable<T>? as side answer that doesn't really answer that question itself. I think this is not enough to qualify this question as duplicate of that one because they ask different things.