ProgrammingHardTCS NQT · Infosys pattern

Does this compile?

Does this compile?
class Base {
    void greet() { System.out.println("Base.greet"); }
}
class Derived extends Base {
    @Override
    void greet() throws java.io.IOException {
        System.out.println("Derived.greet");
        throw new java.io.IOException();
    }
}
  1. A. Yes, it compiles fine
  2. B. No: an override cannot declare a new checked exception not present on the overridden method
  3. C. Yes, but only if Base also declares throws IOException elsewhere
  4. D. No: @Override cannot be combined with a throws clause

Correct answer: B. No: an override cannot declare a new checked exception not present on the overridden method

Base.greet() declares no checked exceptions at all, so Derived's override is forbidden from adding `throws IOException` (a checked exception), since that would let callers who only know about Base's contract be surprised by an unhandled checked exception — this is a compile-time error.

More OOP with C++ and Java questions

Exams that ask this topic