如何在Java 8 Stream中处理异常?
发布时间:2020-12-15 04:38:18 所属栏目:Java 来源:网络整理
导读:我有一个方法,我遍历List并创建List.在这样做时,我调用一个方法(createResult)来给一个Result也抛出CustomException,我将它包装为ResultClassException.但我一直收到一个错误,指出未处理的异常. 我的代码: private ListResult getResultList(ListString res
我有一个方法,我遍历List并创建List.在这样做时,我调用一个方法(createResult)来给一个Result也抛出CustomException,我将它包装为ResultClassException.但我一直收到一个错误,指出未处理的异常.
我的代码: 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); } 有人能说出我做错了什么吗? 解决方法
您的方法可能有太多的责任.您应该考虑将其拆分为仅映射的方法和收集它们的另一个方法.
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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |