ProgrammingHardWipro · Cognizant pattern

Does this compile?

Does this compile?
public class Main {
    public static void main(String[] args) {
        try {
            throw new RuntimeException("x");
        } catch (RuntimeException e) {
            System.out.println("generic");
        } catch (IllegalArgumentException e) {
            System.out.println("specific");
        }
    }
}
  1. A. Yes, and it prints generic
  2. B. No: IllegalArgumentException is unreachable because RuntimeException, a broader supertype, is caught first
  3. C. Yes, and it prints specific
  4. D. No: catch blocks must be ordered alphabetically

Correct answer: B. No: IllegalArgumentException is unreachable because RuntimeException, a broader supertype, is caught first

IllegalArgumentException IS-A RuntimeException, so once the earlier, broader catch(RuntimeException) is present, the later, narrower catch(IllegalArgumentException) can never be reached for ANY exception — javac detects this and rejects it as unreachable code at compile time.

More OOP with C++ and Java questions

Exams that ask this topic