ProgrammingHardProduct-company placement · Java
What happens when this code is compiled?
What happens when this code is compiled?
try { new java.io.FileReader("x.txt"); }
catch (java.io.IOException | Exception e) { System.out.print("caught"); }- A. It compiles and prints caught if the file is missing
- B. It compiles; only IOException is caught
- C. Compile-time error: alternatives in a multi-catch cannot be subclasses of each other
- D. Compile-time error: FileReader does not throw IOException
Correct answer: C. Compile-time error: alternatives in a multi-catch cannot be subclasses of each other
In a multi-catch (A | B) the types must be unrelated; IOException is a subclass of Exception, so the union is rejected. Catching Exception alone would do.
More OOP with C++ and Java questions
- What is printed? java try { throw null; } catch (NullPointerException e) { System.out.print("NPE"); } catch (Exception e) {…
- What is printed? java int i = 0; while (true) { try { i++; if (i == 3) break; } finally { System.out.print(i); } }
- What is printed? java String s = null; switch (s) { case "a": System.out.print("A"); break; default: System.out.print("D"); }
- What is printed? java class Box<T> { static int count = 0; Box() { count++; } } // in main: new Box<String>(); new Box<Integer>(); new…
- Which lines fail to compile? java class G<T> { T[] arr = new T[10]; // L1 T make() { return new T(); } // L2 boolean is(Object o) { return…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(1, 2, 3)); Iterator<Integer> it = l.iterator(); it.next(); it.remove()…