【问题标题】:cant throw Exception from inner try/catch loop LambdaExpresion Java无法从内部 try/catch 循环 Lambda 表达式 Java 中抛出异常
【发布时间】:2016-04-22 01:53:07
【问题描述】:

我有一个名为的表名列表:

List<String> tables = Lists.newArrayList();

我想做的是创建一个连接,然后一个一个地删除所有表。

我的问题是在 stmt.exceuteUpdate(sql) 行 eclipse 中要求我捕捉 SQLException。但是当我尝试抛出同样的异常时, eclipse 在说:未处理的异常类型 SQLException

在我的方法声明中:

throws  Exception, SQLException

请帮助我。可能是什么问题?

try (Statement stmt = data.db.getConnection().createStatement()) {
tables.stream().forEach(tableName -> {
    String sql = "  DELETE  FROM " + tableName;
        int deletedRows = 0;
        try {
            deletedRows = stmt.executeUpdate(sql);
        } catch (Exception e) {
            throw e; // eclipse says:  Unhandled exception type SQLException 
        }
});

我尝试在使用throw e; 时同时捕获 SQLException 或 Exception。但是 eclipse 将此标记为错误!

如果我不使用throw e;,eclipse 不会将其标记为错误,但我确实需要在那里抛出异常。

可能是什么问题?

【问题讨论】:

  • throw new RuntimeException(e); 如果您只想不检查异常
  • 这里似乎根本不需要使用 lambda 表达式。 for (String tableName : tables) 完全一样。

标签: java eclipse exception lambda


【解决方案1】:

您的 lambda 表达式用作 java.util.function.Consumer,它不能从其 accept 方法中抛出检查异常。因此只需抛出一个RuntimeException,例如

catch (Exception e) { 
    throw new IllegalStateException(e);
}

由于这很烦人,您也可以放弃流方法并使用简单的 foreach 循环。

【讨论】:

  • 这对于在另一个线程上执行的 lambdas 来说当然是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-19
  • 1970-01-01
  • 2011-03-28
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多