In C++, the lifetime of an object begins when the constructor finishes successfully. Inside the constructor, the object does not exist yet.
Q: What does emitting an exception from a constructor mean?
A: It means that construction has failed, the object never existed, its lifetime never began. [source]
My question is: Does the same hold true for Java? What happens, for example, if I hand this to another object, and then my constructor fails?
Foo()
{
Bar.remember(this);
throw new IllegalStateException();
}
Is this well-defined? Does Bar now have a reference to a non-object?
The object exists, but it’s not been initialized properly.
This can happen whenever
thisleaks during construction (not just when you throw an exception).It’s a very problematic situation, because some commonly assumed guarantees don’t hold true in this situation (for example
finalfields could seem to change their value during construction).Therefore you should definitely avoid leaking
thisin the constructor.This IBM developerWorks article describes the precautions to take when constructing objects and the reasoning behind those precautions. While the article discusses the subject in the light of multi-threading, you can have similar problems in a single-threaded environment when unknown/untrusted code gets a reference to
thisduring construction.