ProgrammingVery hardProduct-company placement · Java

What happens?

What happens?
class W {
    { if (true) throw new java.io.IOException("io"); }
    W() throws java.io.IOException { }
}
  1. A. It compiles; new W() throws IOException
  2. B. Compile-time error: an initializer cannot throw a checked exception
  3. C. It compiles; the exception is wrapped in ExceptionInInitializerError
  4. D. Compile-time error: W() must catch the IOException

Correct answer: A. It compiles; new W() throws IOException

An instance initializer may throw a checked exception if EVERY constructor of the class declares it, because the initializer runs as part of each constructor.

More OOP with C++ and Java questions

Exams that ask this topic