从 Completable Future 中的 lambda 抛出时未报告的异常
unreported exception when throwing from a lambda in a Completable Future
当我编译下面的代码时,出现以下错误:
/home/prakashs/composite_indexes/src/main/java/com/spakai/composite/TwoKeyLookup.java:22: error: unreported exception NoMatchException; must be caught or declared to be thrown
CompletableFuture<Set<V>> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2));
代码:
public CompletableFuture<Set<V>> lookup(K callingNumber, K calledNumber) throws NoMatchException {
CompletableFuture<Set<V>> calling = callingNumberIndex.exactMatch(callingNumber);
CompletableFuture<Set<V>> called = calledNumberIndex.exactMatch(calledNumber);
CompletableFuture<Set<V>> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2));
return result;
}
public Set<V> findCommonMatch(Set<V> s1, Set<V> s2) throws NoMatchException {
Set<V> intersection = new HashSet<V>(s1);
intersection.retainAll(s2);
if (intersection.isEmpty()) {
throw new NoMatchException("No match found");
}
return intersection;
}
我已经宣布要扔了。我错过了什么?
Checked Exceptions 比 Java promises 老得多,从 Java 8 起不能很好地与它们一起工作。从技术上讲,BiFunction 没有声明抛出任何 checked Exception。因此,您传递给 thenCombine
的 findCommonMatch
也不能抛出它们。
通过从 RuntimeException
继承来取消选中 NoMatchException
。还要从查找方法中删除误导性的 throws
声明——它不会抛出任何东西——封装在 promise 中的代码将抛出,而不是创建 promise 的方法。
Promise 中抛出的异常在设计上对创建它们并订阅它们的代码完全不可见。相反,您通常希望使用未经检查的异常并以特定于特定承诺库的方式处理它们(有关异常处理设施的详细信息,请参阅 CompletionStage 的文档)。
当我编译下面的代码时,出现以下错误:
/home/prakashs/composite_indexes/src/main/java/com/spakai/composite/TwoKeyLookup.java:22: error: unreported exception NoMatchException; must be caught or declared to be thrown
CompletableFuture<Set<V>> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2));
代码:
public CompletableFuture<Set<V>> lookup(K callingNumber, K calledNumber) throws NoMatchException {
CompletableFuture<Set<V>> calling = callingNumberIndex.exactMatch(callingNumber);
CompletableFuture<Set<V>> called = calledNumberIndex.exactMatch(calledNumber);
CompletableFuture<Set<V>> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2));
return result;
}
public Set<V> findCommonMatch(Set<V> s1, Set<V> s2) throws NoMatchException {
Set<V> intersection = new HashSet<V>(s1);
intersection.retainAll(s2);
if (intersection.isEmpty()) {
throw new NoMatchException("No match found");
}
return intersection;
}
我已经宣布要扔了。我错过了什么?
Checked Exceptions 比 Java promises 老得多,从 Java 8 起不能很好地与它们一起工作。从技术上讲,BiFunction 没有声明抛出任何 checked Exception。因此,您传递给 thenCombine
的 findCommonMatch
也不能抛出它们。
通过从 RuntimeException
继承来取消选中 NoMatchException
。还要从查找方法中删除误导性的 throws
声明——它不会抛出任何东西——封装在 promise 中的代码将抛出,而不是创建 promise 的方法。
Promise 中抛出的异常在设计上对创建它们并订阅它们的代码完全不可见。相反,您通常希望使用未经检查的异常并以特定于特定承诺库的方式处理它们(有关异常处理设施的详细信息,请参阅 CompletionStage 的文档)。