我正在尝试传递引发已检查的异常的方法引用:
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; }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句