2016-02-26 235 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的文檔)。