从Completable Future中的lambda投掷时未报告的exception

当我编译下面的代码时,我收到以下错误:

/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> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2)); 

代码:

  public CompletableFuture<Set> lookup(K callingNumber, K calledNumber) throws NoMatchException { CompletableFuture<Set> calling = callingNumberIndex.exactMatch(callingNumber); CompletableFuture<Set> called = calledNumberIndex.exactMatch(calledNumber); CompletableFuture<Set> result = calling.thenCombine(called, (s1, s2) -> findCommonMatch(s1, s2)); return result; } public Set findCommonMatch(Set s1, Set s2) throws NoMatchException { Set intersection = new HashSet(s1); intersection.retainAll(s2); if (intersection.isEmpty()) { throw new NoMatchException("No match found"); } return intersection; } 

我已经宣布它会被抛出。 我错过了什么?

完整代码位于https://github.com/spakai/composite_indexes

Checked Exceptions比Java承诺要早得多,并且从Java 8 开始不适用于它们。从技术上讲, BiFunction不会声明抛出任何已检查的Exception。 因此,您传递给thenCombine也不能抛出它们。

通过inheritanceRuntimeException NoMatchException取消选中NoMatchException 。 同样从查找方法中删除误导性throws声明 – 它不会抛出任何东西 – 被包装在promise中的代码将抛出,而不是创建承诺的方法。

在promises中抛出的exception是设计完全不可见的代码,创建它们并订阅它们。 相反,您通常需要使用未经检查的exception并以某种方式处理它们,特定于特定的promise库(有关其exception处理工具的详细信息,请参阅CompletionStage的文档)。