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) { }- A. A and D
- B. C and D
- C. D only
- 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
- What is printed? java class R implements AutoCloseable { public void close() { throw new IllegalStateException("close"); } } // in main…
- What is printed? java class T { static int a = T.b + 1; static int b = 5; static int c = b + 1; } // in main: System.out.print(T.a + " " +…
- What is printed? java class K { static final int C = 10; static final Integer D = 20; static { System.out.print("K "); } } // in main…
- Which lines fail to compile? java interface I { static String id() { return "I"; } default String name() { return "N"; } } class C…
- What is printed? cpp struct B { virtual string who() const { return "B"; } }; struct D : B { string who() const override { return "D"; }…
- What is printed? cpp struct M { M() { cout << "m"; } ~M() { cout << "~m"; } }; struct B { B() { cout << "b"; f(); } virtual ~B() { cout <<…