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

查看:28
本文介绍了引发异常的 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

我将如何定义此引用?

推荐答案

您需要执行以下操作之一.

You'll need to do one of the following.

  • 如果是您的代码,则定义您自己的功能接口来声明已检查的异常:

  • 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) 包装在未声明已检查异常的方法中:

  • Otherwise, wrap Integer myMethod(String s) in a method that doesn't declare a checked exception:

    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天全站免登陆