【发布时间】:2017-09-09 01:22:10
【问题描述】:
我有一个遍历列表并创建列表的方法。这样做时,我调用了一个方法(createResult)来给出一个结果,它也会抛出我包装为 ResultClassException 的 CustomException。但是我一直收到一个错误提示 Unhandled Exception。
我的代码:
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);
}
谁能告诉我我做错了什么?
【问题讨论】:
-
ResultClassException不是RuntimeException的子类或resultRepository.get(resultName)都会引发检查异常。您不能从forEach的 lambda 中抛出已检查的异常,因为此 lambda 不会对应于Consumer功能接口。 -
我在您的代码中看不到任何流,只有
forEach。为什么不使用常规的for循环?
标签: java exception java-8 java-stream throws