Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我如何编写lambda表达式,该表达式在不使用try{}catch{}块的情况下重新调用已检查的异常?_Java_Exception_Lambda_Try Catch - Fatal编程技术网

Java 我如何编写lambda表达式,该表达式在不使用try{}catch{}块的情况下重新调用已检查的异常?

Java 我如何编写lambda表达式,该表达式在不使用try{}catch{}块的情况下重新调用已检查的异常?,java,exception,lambda,try-catch,Java,Exception,Lambda,Try Catch,我有一个lambda表达式,它可以抛出一个IOException: Function<String, List<String>> readFile = path-> { try { return Files.readAllLines( Paths.get((String) path), Charset.forName("UTF-8")); } catch (IOE

我有一个lambda表达式,它可以抛出一个
IOException

    Function<String, List<String>> readFile = path-> {
        try {
            return Files.readAllLines(
                    Paths.get((String) path), Charset.forName("UTF-8"));
        } catch (IOException e) {
            return null;
        }
    };
唯一的问题是,我不能定义自己的接口/类,只能使用Java API提供的接口


这可能吗?

如果要重新显示例外,可以使用RuntimeException。 把这个加到你的钓身上

throw new RuntimeException(e);

由于
Function.apply
不会抛出选中的异常,因此无法执行此操作

。。。以合法的方式。但是,如果你能承担风险

,你可以考虑“偷偷摸摸”。
interface FunctionX<T,R, X extends Exception> extends Function<T,R>
{
    R applyX(T t) throws X;

    @Override
    default R apply(T t)
    {
        try
        {
            return applyX(t);
        } 
        catch (Exception x)
        {
            throw Util.sneakyThrow(x);
        }
    }

    public static <T,R,X extends Exception> 
    FunctionX<T,R,X> of(FunctionX<T,R,X> f){ return f; }

}

// Util.java

public static RuntimeException sneakyThrow(Throwable t)
{
    throw Util.<RuntimeException>sneakyThrow0(t);
}
@SuppressWarnings("unchecked")
private static <T extends Throwable> T sneakyThrow0(Throwable t) throws T
{
    throw (T)t;
}
接口函数x扩展函数
{
R applyX(T)抛出X;
@凌驾
默认R应用(T)
{
尝试
{
归苹果(t);
} 
捕获(异常x)
{
抛出Util.skillythrow(x);
}
}
公共静电
(functionxf){返回f;}
}
//Util.java
公共静态运行时异常(throw)(Throwable t)
{
抛出Util.skillythrow0(t);
}
@抑制警告(“未选中”)
私有静态T sleekythrow0(可丢弃的T)抛出T
{
投掷(T)T;
}
用法示例

    Function<String, List<String>> readFile = FunctionX.of( path-> {
        return Files.readAllLines(
            Paths.get(path), Charset.forName("UTF-8"));
    } );

    readFile.apply("/no-file");
Function readFile=FunctionX.of(路径->{
return Files.readAllLines(
path.get(path)、Charset.forName(“UTF-8”);
} );
readFile.apply(“/无文件”);

它仍将定义新的接口,这是我想要避免的。您可以将其用作函数。
    Function<String, List<String>> readFile = FunctionX.of( path-> {
        return Files.readAllLines(
            Paths.get(path), Charset.forName("UTF-8"));
    } );

    readFile.apply("/no-file");