ProgrammingVery hardProduct company OA

Does this compile (Java 7+)?

Does this compile (Java 7+)?
static void m() throws java.io.IOException, java.sql.SQLException {
    try {
        if (Math.random() < 2) throw new java.io.IOException();
        else throw new java.sql.SQLException();
    } catch (Exception e) {
        throw e;
    }
}
  1. A. No: throw e; requires e's declared type Exception, so m() must declare throws Exception
  2. B. Yes, but only because Exception itself is unchecked
  3. C. No: you can never rethrow a caught Exception without a RuntimeException wrapper
  4. D. Yes: 'more precise rethrow' lets the compiler see e can only be IOException or SQLException, matching the throws clause

Correct answer: D. Yes: 'more precise rethrow' lets the compiler see e can only be IOException or SQLException, matching the throws clause

Since Java 7, if a caught multi-type variable like e is never reassigned, the compiler tracks the narrower set of types the try block could actually throw (IOException or SQLException) for rethrow analysis, so this compiles despite e's static type being Exception.

More OOP with C++ and Java questions

Exams that ask this topic