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"); }
  1. A. It compiles and prints caught if the file is missing
  2. B. It compiles; only IOException is caught
  3. C. Compile-time error: alternatives in a multi-catch cannot be subclasses of each other
  4. 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

Exams that ask this topic