2017-04-13 13 views
3

私はリストをたどってリストを作成する方法を持っています。その間、Result(ResultRassult)を呼び出してResultを呼び出してResultClassExceptionとしてラッピングするCustomExceptionをスローします。しかし、私は、未処理の例外と言うエラーが発生し続ける。Java 8 Streamで例外を処理する方法は?

マイコード:誰かが私が間違っているの何

private List<Result> getResultList(List<String> results) throws ResultClassException { 
    List<Result> resultList = new ArrayList<>(); 
     results.forEach(
       (resultName) -> { 
        if (!resultRepository.contains(resultName)) { 
         try { 
          final Result result = createResult(resultName); 
          resultList.add(result); 
         } catch (CustomException e) { 
          throw new ResultClassException("Error",e); 
         } 

        } else { 
         resultList.add(resultRepository.get(resultName)); 
         log.info("Result {} already exists.", resultName); 
        } 
       } 
     ); 
     return Collections.unmodifiableList(resultList); 
    } 

を伝えることはできますか?

+3

'ResultClassException'は' RuntimeException'のサブクラスでも、resultRepository.get(resultName)でもチェック例外をスローします。このラムダは 'Consumer'関数インタフェースに対応しないので、' forEach'のラムダ内からチェック例外を投げることはできません。 –

+2

あなたのコードにはストリームが全く見当たりません。ちょうど 'forEach'です。通常の 'for'ループを使わないのはなぜですか? – shmosel

答えて

4

あなたはおそらく、あなたの方法にあまりにも多くの責任を持っています。マップする方法とマップする方法に分割することを検討する必要があります。

private List<Result> getResultList(List<String> names) throws ResultClassException { 
    try { 
    return names.stream() 
     .map(this::getOrCreateResult) 
     .collect(collectingAndThen(toList(), Collections::unmodifiableList)); 
    } catch (RuntimeException e) { 
    if (e.getCause() instanceof CustomException) { 
     throw new ResultClassException("Error", e.getCause()); 
    } 
    throw e; 
    // Or use Guava's propagate 
    } 
} 

private Result getOrCreateResult(String name) { 
    if (!resultRepository.contains(name)) { 
    try { 
     return createResult(name); 
    } catch (CustomException e) { 
     throw new RuntimeException(e); 
    } 
    } else { 
    log.info("Result {} already exists.", name); 
    return resultRepository.get(name); 
    } 
} 
0

私はRuntimeExceptionを使用することをお勧めしません。 getResultList(...)の呼び出しメソッドでResultClassExceptionを処理してください。

0

Java 8のラムダ式では、内部クラスを表現しています。したがって、例外は匿名の内部クラスの内部にスローされます。 を追加する場所に新しいResultClassException( "Error"、e)を追加します。

     Thread.getAllStackTraces() 
          .keySet() 
          .stream() 
          .map(Thread::getStackTrace) 
          .map(Arrays::asList) 
          .forEach(list -> System.out.println(list.stream() 
                    .map(i -> i.toString()) 
                    .collect(Collectors.joining("\n\t")))); 

と呼ばれているスレッドを参照してください。例外がラムダで期待した範囲外であることがわかります。ストリームが多くのスレッドを作成していて、例外が必要なスレッドの一部ではないことがわかります。 あなたはそのようなあなたの方法をラップすることができます Java 8: How do I work with exception throwing methods in streams?

関連する問題