Given this java 8 code
public Server send(String message) {
sessions.parallelStream()
.map(Session::getBasicRemote)
.forEach(basic -> {
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
});
return this;
}
how do we properly make this IOException
be delegated up the stack of the method call? (in nutshell how to make this method throw this IOException
?)
Lambdas in java does not look very friendly to error handling...
I wrote an extension to the Stream API which allows for checked exceptions to be thrown.
My approach would be to sneakily throw it from the lambda, but take care to have the
send
method declare it in itsthrows
clause. Using theExceptional
class I posted here:This way you're effectively making the compiler "look away" for just a bit, disabling its exception checking at one spot in your code, but by declaring the exception on your
send
method, you restore the regular behavior for all its callers.The problem is indeed that all
@FunctionalInterface
s used in lambdas do not allow exceptions to be thrown, save for unchecked exceptions.One solution is using a package of mine; with it, your code can read: