0

I have this code:

private void save(List<String> items) throws IOException {
        try (FileWriter fileWriter = new FileWriter(file, true)) {
            for (String item : items) {
                fileWriter.write(item);
            }

            // Error for: "Unhandled exception: java.io.Exception"
            items.stream().forEach(fileWriter::write);
        }
    }

It should write each element from the list passed to file.

I'm learning java streams and wanted to write each element with forEach function but run into strange error. Even my function throws IOException my IDE and compiled still complains about uncaught exception.

Do you need to catch it in lambda itself? Can it be thrown to parent?

Faustas Butkus
  • 291
  • 1
  • 5
  • 14
  • 1
    Possible duplicate of [Why can't I throw an exception in a Java 8 lambda expression?](https://stackoverflow.com/questions/37726874/why-cant-i-throw-an-exception-in-a-java-8-lambda-expression) and [Java 8 method reference unhandled exception](https://stackoverflow.com/questions/25643348/java-8-method-reference-unhandled-exception). – Slaw Aug 18 '18 at 14:35
  • See dupe, but that’s the deal with lambdas - they can’t throw checked exceptions. – Bohemian Aug 18 '18 at 15:16

0 Answers0