抛出异常的Java 8 Lambda函数?我知道如何创建对具有String参数并返回int它是:Function<String, Integer>但是,如果函数抛出异常,则此操作不起作用,例如,它被定义为:Integer myMethod(String s) throws IOException我将如何定义这个引用?
3 回答
慕后森
TA贡献1802条经验 获得超5个赞
如果是您的代码,那么定义您自己的函数接口来声明选中的异常: @FunctionalInterfacepublic interface CheckedFunction<T, R> { R apply(T t) throws IOException;}并使用它: void foo (CheckedFunction f) { ... }否则,包装 Integer myMethod(String s)在不声明选中异常的方法中: public Integer myWrappedMethod(String s) { try { return myMethod(s); } catch(IOException e) { throw new UncheckedIOException(e); }}然后: Function<String, Integer> f = (String t) -> myWrappedMethod(t);
或: Function<String, Integer> f = (String t) -> { try { return myMethod(t); } catch(IOException e) { throw new UncheckedIOException(e); } };
慕的地10843
TA贡献1785条经验 获得超8个赞
ConsumerFunction
Consumer):
@FunctionalInterfacepublic interface ThrowingConsumer<T> extends Consumer<T> {
@Override
default void accept(final T elem) {
try {
acceptThrows(elem);
} catch (final Exception e) {
// Implement your own exception handling logic here..
// For example:
System.out.println("handling an exception...");
// Or ...
throw new RuntimeException(e);
}
}
void acceptThrows(T elem) throws Exception;}final List<String> list = Arrays.asList("A", "B", "C");forEach
final Consumer<String> consumer = aps -> {
try {
// maybe some other code here...
throw new Exception("asdas");
} catch (final Exception ex) {
System.out.println("handling an exception...");
}};list.forEach(consumer);final ThrowingConsumer<String> throwingConsumer = aps -> {
// maybe some other code here...
throw new Exception("asdas");};list.forEach(throwingConsumer);list.forEach((ThrowingConsumer<String>) aps -> {
// maybe some other code here...
throw new Exception("asda");});更新System.out...throw RuntimeException
list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));
添加回答
举报
0/150
提交
取消
