ProgrammingHardWipro · Cognizant pattern

Does this compile?

Does this compile?
public class Main {
    public static void main(String[] a) {
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            System.out.print("generic");
        } catch (RuntimeException e) {
            System.out.print("specific");
        }
    }
}
  1. A. Compiles and prints generic
  2. B. Compiles and prints specific
  3. C. No: catch (RuntimeException e) is unreachable because the preceding catch (Exception e) already covers it
  4. D. No: you cannot catch RuntimeException separately from Exception

Correct answer: C. No: catch (RuntimeException e) is unreachable because the preceding catch (Exception e) already covers it

Java requires catch clauses to be ordered from most specific to most general. Since RuntimeException is a subtype of Exception, placing catch (Exception e) first makes the later, more specific catch (RuntimeException e) unreachable code, which is a compile-time error.

More OOP with C++ and Java questions

Exams that ask this topic