ProgrammingHardHCL · Tech Mahindra pattern

A Java class's constructor runs `this.handle = acquire();` and then later throws an exception before returning. Which statement is correct?

  1. A. The finalize()/Cleaner mechanism is guaranteed to run immediately when the constructor throws
  2. B. try-with-resources on the caller's side will close handle even though the object reference was never assigned
  3. C. The object reference is never produced, so nothing outside the constructor can release handle automatically — the constructor itself must release it (e.g. in a catch block) or it leaks until an unreliable finalizer/cleaner eventually runs
  4. D. Java automatically calls a destructor on the partially built object to release handle

Correct answer: C. The object reference is never produced, so nothing outside the constructor can release handle automatically — the constructor itself must release it (e.g. in a catch block) or it leaks until an unreliable finalizer/cleaner eventually runs

Java has no destructors. If a constructor throws after acquiring a resource, the new object is discarded without ever being returned, so nothing automatically frees that resource — a leak unless the constructor itself catches the failure and releases the resource before rethrowing.

More OOP with C++ and Java questions

Exams that ask this topic