2016-02-26 227 views
0

当我编译下面的代码,我收到以下错误:没有报告异常

/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

回答

2

检查异常是比Java的承诺大年纪了,不也与他们的Java 8.从技术上讲的工作,BiFunction没有声明抛出任何checked异常。因此,您传递给thenCombinefindCommonMatch也不能丢弃它们。

通过从RuntimeException继承使得NoMatchException未被选中。同时从查找方法中删除误导性的throws声明 - 它不会抛出任何东西 - 被封装在诺言中的代码将抛出,而不是方法创建诺言。

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