ProgrammingVery hardProduct company interview · GATE level

Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.)

Which of these four fragments compiles? (FileReader's constructor throws FileNotFoundException, a subclass of IOException.)
// A
try { new FileReader("f"); }
catch (Exception e) { }
catch (IOException e) { }
// B
try { new FileReader("f"); }
catch (FileNotFoundException | IOException e) { }
// C
try { int x = 1; }
catch (IOException e) { }
// D
try { new FileReader("f"); }
catch (IOException | RuntimeException e) { }
  1. A. A and D
  2. B. C and D
  3. C. D only
  4. D. B and D

Correct answer: C. D only

A: the catch for IOException is unreachable because Exception, listed first, already catches it - a compile error. B: the alternatives of a multi-catch must not be subclasses of each other, and FileNotFoundException is a subclass of IOException. C: it is an error to catch a checked exception that the try block cannot throw (this rule does not apply to Exception, Throwable or unchecked exceptions). D is fine: IOException and RuntimeException are unrelated.

More OOP with C++ and Java questions

Exams that ask this topic