从方法参考中捕获异常

lef*_*loh 2 java lambda java-8

我正在尝试传递一个抛出已检查异常的方法引用:

Files.list((Paths.get("/some/path"))).map(Files::readAllLines);
Run Code Online (Sandbox Code Playgroud)

如何处理此异常(不将方法引用包装在处理exeption的方法中).

Rog*_*gue 8

如果你试图捕获特定值的异常,.map我不建议使用方法引用,而是使用lambda:

Files.list((Paths.get("/some/path"))).map((someVal) -> {

    try {
        //do work with 'someVal'
    } catch (YourException ex) {
        //handle error
    }

});
Run Code Online (Sandbox Code Playgroud)

如果您想在之后重新抛出异常,可以通过框子手动引用错误:

//using the exception itself
final Box<YourException> e = new Box<>();
Files.list((Paths.get("/some/path"))).map((someVal) -> {

    try {
        //do work with 'someVal'
    } catch (YourException ex) {
        //handle error
        e.setVar(ex);
    }

});
if (e.getVar() != null) {
    throw e.getVar();
}

class Box<T> {
    private T var;
    public void setVar(T var) { this.var = var; }
    public T getVar() { return this.var; }
}
Run Code Online (Sandbox Code Playgroud)