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");
});- A. It compiles because the method declares throws IOException
- B. It compiles; forEach wraps the exception in RuntimeException
- C. Compile-time error: unreported exception IOException in the lambda
- 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
- Which line fails to compile? java List<?> l = new ArrayList<String>(); l.add(null); // L1 l.add("x"); // L2 Object o = l.isEmpty() ? null…
- Which line fails to compile? java class Fruit implements Comparable<Fruit> { public int compareTo(Fruit o) { return 0; } } class Apple…
- Which line fails to compile? java // Java 16 or later Object o = "hello"; if (o instanceof String s && s.length() > 3)…
- What is printed? java Set<Short> s = new HashSet<>(); for (short i = 0; i < 5; i++) { s.add(i); s.remove(i - 1); }…
- What is printed? java Map<Long, String> m = new HashMap<>(); m.put(1L, "one"); System.out.print(m.get(1) + " " + m.get(1L) + " " +…
- What is printed? java List<Character> l = new ArrayList<>(List.of('a', 'b')); System.out.print(l.contains('a') + " " + l.contains(97) + "…