3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
如果是您的代碼,那么定義您自己的函數(shù)接口來(lái)聲明選中的異常: @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); } };

TA貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超8個(gè)贊
Consumer
Function
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)));
添加回答
舉報(bào)