How to handle exceptions in Java 8 stream?
•
Java
I have a method. I traverse the list and create the list In doing so, I call a method (createresult) to throw a customexception to a result, which I wrap as resultclassexception But I keep getting an error indicating an unhandled exception
My code:
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); }
Can anyone tell me what I did wrong?
Solution
Your approach may have too many responsibilities You should consider splitting it into mapping only methods and another method to collect them
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); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码