ProgrammingVery hardProduct-company placement · Java

What happens when this method is compiled (Java 7 or later)?

What happens when this method is compiled (Java 7 or later)?
static void f() throws java.io.IOException {
    try {
        if (Math.random() < 2) throw new java.io.IOException();
    } catch (Exception e) {
        throw e;
    }
}
  1. A. Compile-time error: unreported exception Exception
  2. B. Compile-time error: e must be declared final
  3. C. It compiles: e is rethrown precisely as the IOException the try block can throw
  4. D. It compiles only if f() declares throws Exception

Correct answer: C. It compiles: e is rethrown precisely as the IOException the try block can throw

With precise rethrow, rethrowing an effectively final catch parameter is checked against the exceptions the try block can actually throw (IOException plus unchecked ones), not against the declared catch type.

More OOP with C++ and Java questions

Exams that ask this topic