【问题标题】:unreported exception when throwing from a lambda in a Completable Future从 Completable Future 中的 lambda 抛出时未报告的异常
【发布时间】:2018-08-21 16:31:30
【问题描述】:

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

/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;
    }

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

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

【问题讨论】:

    标签: java future completable-future


    【解决方案1】:

    Checked Exceptions 比 Java Promise 早得多,并且在 Java 8 中不能很好地与它们一起工作。从技术上讲,BiFunction 没有声明抛出任何已检查异常。因此,您传递给thenCombinefindCommonMatch 也不能扔掉它们。

    通过从RuntimeException 继承来取消选中NoMatchException。还要从查找方法中删除误导性的 throws 声明——它不会抛出任何东西——封装在 promise 中的代码将抛出,而不是创建 promise 的方法。

    promise 中抛出的异常在设计上对代码完全不可见,代码创建并订阅它们。相反,您通常希望使用未经检查的异常并以特定于特定 Promise 库的方式处理它们(有关其异常处理设施的详细信息,请参阅CompletionStage 的文档)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多