抛出异常的Java 8 Lambda函数? [英] Java 8 Lambda function that throws exception?

查看:637
本文介绍了抛出异常的Java 8 Lambda函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何创建对具有 String 参数的方法的引用,并返回 int ,它是:

I know how to create a reference to a method that has a String parameter and returns an int, it's:

Function<String, Integer>

但是,如果函数抛出异常,这不起作用,比如它被定义为:

However, this doesn't work if the function throws an exception, say it's defined as:

Integer myMethod(String s) throws IOException

我如何定义这个参考?

推荐答案

你需要做一个以下。


  • 如果是你的代码,那么定义你自己的功能接口来声明检查的异常

  • If it's your code, then define your own functional interface that declares the checked exception

@FunctionalInterface
public 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);
            }
        };
    


  • 这篇关于抛出异常的Java 8 Lambda函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆