ProgrammingHardProduct-company placement · Java

What happens when this is compiled (inside a method declared throws IOException)?

What happens when this is compiled (inside a method declared throws IOException)?
List<String> files = List.of("a.txt");
files.forEach(f -> {
    if (f.isEmpty()) throw new java.io.IOException("x");
});
  1. A. It compiles because the method declares throws IOException
  2. B. It compiles; forEach wraps the exception in RuntimeException
  3. C. Compile-time error: unreported exception IOException in the lambda
  4. D. It compiles but always throws IOException

Correct answer: C. Compile-time error: unreported exception IOException in the lambda

The lambda implements Consumer.accept, which declares no checked exceptions; the enclosing method's throws clause does not apply to the lambda body. The exception must be caught or wrapped inside the lambda.

More OOP with C++ and Java questions

Exams that ask this topic