7

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?

3 Answers 3

8

The object exists, but it's not been initialized properly.

This can happen whenever this leaks 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 final fields could seem to change their value during construction).

Therefore you should definitely avoid leaking this in 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 this during construction.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 - but "leaking" is called (unsafe) "publishing" in this case; e.g. in Bloch. Also it would be a good idea to explain this in more depth.
1

You should never open resources like a file writer in your constructor. Create a init method instead and do it from there. Then you're safe.

2 Comments

"Then you're safe". That statement is patently false!! There are lots of other things that can cause exceptions in a constructor; e.g. illegal argument, NPE, array index, etc, and even stack overflow or out of memory errors.
That's good advice but there are other cases where you might want a constructor to fail. For example, I want a parallel iterator as described here stackoverflow.com/questions/3137944/… so I want to check the lists are the same size at construction time.
0

This code is not exception safe and neither would be exception safe in C++. It's same bug regardless of the language you use.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.