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 {}
}- A. Compile-time error: FileNotFoundException is unrelated to IOException
- B. Compiles fine: FileNotFoundException is a subtype of IOException, a narrowing of the declared checked exceptions, which is allowed
- C. Compiles only if risky() also declares throws IOException
- 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
- What is printed? java public class Main { public static void main(String[] args) { Object o = "text"; try { Integer n = (Integer) o…
- What is printed? java public class Main { static int divide(int a, int b) { try { return a / b; } catch (ArithmeticException e) { return…
- What is printed? java import java.util.; public class Main { public static void main(String[] args) { Map<String, Integer> m = new…
- What is printed? java public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder("abc"); try {…
- What is printed? java class A { A() { System.out.print("A "); } } class B extends A { B() { System.out.print("B "); } B(int x) { this()…
- What happens when this is compiled? java class A { A(int x) { System.out.print("A(int) "); } } class B extends A { B() {…