ProgrammingHardIBM · Deloitte pattern

What happens when this is compiled?

What happens when this is compiled?
class Base {
    void risky() throws java.io.IOException {}
}
class Sub extends Base {
    @Override
    void risky() throws java.io.FileNotFoundException {}
}
  1. A. Compile-time error: FileNotFoundException is unrelated to IOException
  2. B. Compiles fine: FileNotFoundException is a subtype of IOException, a narrowing of the declared checked exceptions, which is allowed
  3. C. Compiles only if risky() also declares throws IOException
  4. D. Compile-time error: overriding methods cannot change the throws clause at all

Correct answer: B. Compiles fine: FileNotFoundException is a subtype of IOException, a narrowing of the declared checked exceptions, which is allowed

FileNotFoundException extends IOException, so it is narrower, not broader. Java allows an override to declare the same, narrower, or no checked exceptions compared to the method it overrides, so this compiles cleanly.

More OOP with C++ and Java questions

Exams that ask this topic