ProgrammingHardAccenture · Capgemini technical pattern

What happens when this Java code is compiled?

What happens when this Java code is compiled?
try {
    FileReader r = new FileReader("a.txt");
} catch (Exception e) {
    System.out.print("E");
} catch (IOException e) {
    System.out.print("IO");
}
  1. A. Compilation error: the IOException catch block is unreachable
  2. B. It compiles; IO is printed if the file is missing
  3. C. It compiles; E is printed if the file is missing
  4. D. It compiles with only a warning

Correct answer: A. Compilation error: the IOException catch block is unreachable

Catch blocks are tried in order, and Exception already catches every IOException, so the second block can never run. Java treats this as an error; the more specific catch must come first.

More OOP with C++ and Java questions

Exams that ask this topic