在“完全未来”中从lambda抛出时发生未报告的异常 [英] unreported exception when throwing from a lambda in a Completable Future

查看:83
本文介绍了在“完全未来”中从lambda抛出时发生未报告的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我编译下面的代码时,出现以下错误:

When I compile the code below, I get the following error:

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

我已经宣布将其抛出。我缺少什么?

I am already declaring it to be thrown. What am I missing?

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

推荐答案

已检查的异常比Java的承诺要早得多,并且不会从Java 8开始,它们可以很好地与它们协同工作。从技术上来说, BiFunction 不声明引发任何检查的异常。这样,您传递给 thenCombine findCommonMatch 也不能抛出它们。

Checked Exceptions are much older than Java promises and do not work well with them as of Java 8. Technically speaking, BiFunction does not declare throwing any checked Exception. As such, your findCommonMatch, which you pass to thenCombine, can not throw them either.

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

Make NoMatchException unchecked by inheriting from RuntimeException. Also remove the misleading throws declaration from the lookup method — it is not throwing anything — the code, being encapsulated within promise, is going to throw, not method creating promise.

根据设计,在promise中引发的异常对于代码完全不可见,可以创建它们并对其进行订阅。通常,通常希望您使用未经检查的异常并以特定于特定的Promise库的方式处理它们(请参见 CompletionStage 了解其异常处理工具的详细信息。)

Exceptions thrown within promises are by design completely invisible to code, that creates them and subscribes to them. Instead you are usually expected to use unchecked exceptions and handle them in a way, specific for particular promise library (see documentation of CompletionStage for details on it's exception handling facilities).

这篇关于在“完全未来”中从lambda抛出时发生未报告的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆