unreported exception when throwing from a lambda in a Completable Future

做~自己de王妃 提交于 2019-12-17 21:24:09

问题


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));

The code:

 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?

The full code is in https://github.com/spakai/composite_indexes


回答1:


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.

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.

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).



来源:https://stackoverflow.com/questions/35643193/unreported-exception-when-throwing-from-a-lambda-in-a-completable-future

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!