我正在尝试传递引发已检查的异常的方法引用:
Files.list((Paths.get("/some/path"))).map(Files::readAllLines);
我该如何处理此异常(不将方法引用包装在处理异常的方法中)。
最佳答案
如果您尝试在.map
中捕获特定值的异常,我将不建议使用方法引用,而应使用lambda:
Files.list((Paths.get("/some/path"))).map((someVal) -> {
try {
//do work with 'someVal'
} catch (YourException ex) {
//handle error
}
});
如果您想在之后重新抛出异常,则可以通过在框中引用错误来手动进行:
//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; }
}
关于java - 从方法引用中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23220043/