【发布时间】:2016-11-23 12:34:36
【问题描述】:
在我的代码中,我有 try/catch 块并且我正在捕获 mysql 异常。然而,它仍然抱怨我们需要在 foreach 循环中再次处理这个异常。
正如您在此处看到的正常 for 循环(在 foreach 逻辑之后),我们不需要专门处理它。有人能解释一下这背后的逻辑吗?
try (Connection connection = DAOUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(query)) {
IntStream.range(0, statuses.size())
.forEach(i -> statement.setString(i+1 , statuses.get(i)));
for (int i = 0; i < statuses.size(); ++i) {
statement.setString(i + 1, statuses.get(i));
}
return constructAPISummaryList(statement);
} catch (SQLException e) {
throw new APIMgtDAOException(e);
}
}
错误发生在.forEach(i -> statement.setString(i+1, statuses.get(i)));
错误消息:“未处理的异常:java.sql.SQLException”
【问题讨论】:
-
请不要将图片作为代码发布,See this meta post。
-
很抱歉。我只是想向您展示浏览器如何抱怨 sqlException。
-
@Tunaki 这个问题看起来不同,因为 OP 询问他何时已经添加了一个 try-catch 为什么它仍然会给出编译错误。
-
@grsdev7 不,因为问题不是来自 try-catch 块的存在,而是来自 lambda,其目标类型是函数式接口,其中函数式方法未声明抛出已检查的异常。还有this question OP 也有try-catch,但当前的副本将以对我更有帮助的方式解决这个问题。
-
@Tunaki :正确,上述评论中的问题是重复的。
标签: java