为了账号安全,请及时绑定邮箱和手机立即绑定

抛出异常的Java 8 Lambda函数?

抛出异常的Java 8 Lambda函数?

一只萌萌小番薯 2019-06-25 16:28:21
抛出异常的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);
            }
        };


查看完整回答
反对 回复 2019-06-25
?
慕的地10843

TA贡献1785条经验 获得超8个赞

实际上你可以扩展Consumer(和Function(等等)有一个处理异常的新接口-使用Java 8的默认方法!

考虑这个接口(扩展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)使用一些抛出异常的代码,您通常会设置一个try/catch块:

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);

但是使用这个新接口,您可以使用lambda表达式实例化它,编译器不会抱怨:

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),而Durian的错误允许您通过一组大型实用方法动态地应用策略。谢谢分享它,@NedTwigg!

样本使用情况:

list.forEach(Errors.rethrow().wrap(c -> somethingThatThrows(c)));


查看完整回答
反对 回复 2019-06-25
  • 3 回答
  • 0 关注
  • 1301 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号