1

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

Didier L
  • 18,905
  • 10
  • 61
  • 103
spakai
  • 303
  • 1
  • 2
  • 17

1 Answers1

4

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

user1643723
  • 4,109
  • 1
  • 24
  • 48
  • Here is a solution that allows you to use checked exceptions without reducing the readability of your code: https://stackoverflow.com/a/49705336/14731 – Gili Apr 07 '18 at 08:28