-1

In my code i have try/catch block and there i'm catching mysql exception. However still its complaining that we need to handle this exception again within foreach loop.

As you can see here for normal for loop(after foreach logic) we dont need to handle it specifically. Can someone explain me the logic behind this?

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);
    } 
}

Error occurs at .forEach(i -> statement.setString(i+1, statuses.get(i)));

Error message: "Unhandled exception: java.sql.SQLException"

Magisch
  • 7,312
  • 9
  • 36
  • 52
sanjeewa.190
  • 360
  • 2
  • 8
  • Please don't post images as code, [See this meta post](https://meta.stackoverflow.com/q/285551/3933332). – Bhargav Rao Nov 23 '16 at 12:41
  • Sorry about that. I just wanted to show you how browser complains about sqlException. – sanjeewa.190 Nov 23 '16 at 12:43
  • 1
    @Tunaki this question looks different as OP is asking when he has already added one try-catch why still it gives compile error. – Goro Nov 23 '16 at 12:55
  • @grsdev7 No, because the problem doesn't come from the presence of the try-catch block, but from the lambda, whose target type is a functional interface where the functional method does not declare to throw a checked exception. There is also [this question](http://stackoverflow.com/questions/32034591/java-compiler-complaining-about-unreported-ioexception) where the OP had the try-catch also, but the current duplicate will address the question in a more helpful manner to me. – Tunaki Nov 23 '16 at 13:01
  • @Tunaki : Correct, question in mentioned above comment is duplicate. – Goro Nov 23 '16 at 13:04

1 Answers1

-1

If you are in foreach, you need to do another try block. You can replace the foreach to a common for or put your try block only inside the foreach block.

Eduardo
  • 3
  • 1
  • 4