The built-in class Functiondoes not allow you to throw thrown exceptions, as you can see from the method signature apply().
However, you can easily define your own @FunctionalInterface, which allows you to throw exceptions, for example:
@FunctionalInterface
public interface CheckedFunction<U,V> {
public V apply(U u) throws Exception;
}
And make a lambdavariable a instead CheckedFunction.
, Function - , , RuntimeException s, :
Function<Foo,Bar> f = foo -> {
try {
return foo.methodThatCanThrow();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
};
, , , .