我有个功能
public ShoppingCart fetchCart(Long storeId) throw NotFoundException {
///
}然后,我试图将这个函数分配给另一个函数,方法是
Function<Long, ShoppingCart> func = e -> {
fetchCart(e)
}但它总是告诉我这个例外是不被处理的。但是,当我试图在函数赋值周围添加try/ ShoppingCart>时,我的“ShoppingCart>函数”不会得到异常。
有没有办法做到这一点,同时也捕获原始函数的异常?谢谢!
更多的背景。我这样做是因为我希望函数被赋予另一个函数作为参数,所以这个函数可以另一个函数并行运行。类似于比较这些函数的值,甚至它们的异常。因此,这个函数是必要的,不能在fetchCart中捕获。
发布于 2021-01-28 20:48:47
我认为您的问题是NotFoundException是一个检查异常。检查的异常(不是RuntimeException子类)不能在lambda中抛出。解决方法是捕获它并在RuntimeException中重新抛出,作为它的原因。
例:
Function<Long, ShoppingCart> func = e -> {
try {
return fetchCart(e);
} catch (NotFoundException ex) {
RuntimeException re = new RuntimeException();
re.initCause(ex);
throw re;
}
return null;
};然后,当您要捕获runtimeException时,您必须处理它的原因。
try {
/// call func here
} catch(Exception e) {
((NotFoundException)e.getCause()).printStackTrace();
}发布于 2021-01-28 20:46:28
您可以将异常包装为运行时异常,然后由调用方处理此运行时异常。
Function<Long, ShoppingCart> func = e -> {
try {
return fetchCart(e);
} catch (NotFoundException notFoundException) {
throw new RuntimeException(notFoundException);
}
}然后,一个文件中的完整代码将是:
import java.util.function.Function;
public class ShoppinCartCaller {
public ShoppingCart fetchCart(Long storeId) throws NotFoundException {
return null;
};
public static class NotFoundException extends Exception {
}
public static class ShoppingCart {
}
Function<Long, ShoppingCart> func = e -> {
try {
return fetchCart(e);
} catch (NotFoundException notFoundException) {
throw new RuntimeException(notFoundException);
}
};
}https://stackoverflow.com/questions/65944705
复制相似问题