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
Probably, a better and more functional way is to wrap exceptions and propagate them further in the stream. Take a look at the Try type of Vavr for example.
Example:
interface CheckedFunction {
O apply(I i) throws Exception; }
static Function unchecked(CheckedFunction f) {
return i -> {
try {
return f.apply(i);
} catch(Exception ex) {
throw new RuntimeException(ex);
}
} }
fileNamesToRead.map(unchecked(file -> Files.readAllLines(file)))
OR
@SuppressWarnings("unchecked")
private static T throwUnchecked(Exception e) throws E {
throw (E) e;
}
static Function unchecked(CheckedFunction f) {
return arg -> {
try {
return f.apply(arg);
} catch(Exception ex) {
return throwUnchecked(ex);
}
};
}
2nd implementation avoids wrapping the exception in a RuntimeException
. throwUnchecked
works because almost always all generic exceptions are treated as unchecked in java.