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?
JavaObject Oriented ProgrammingProgramming. Yes, constructors are allowed to throw an exception in Java. A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class.
The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
You would catch the exception in the calling code, not in the constructor. Exceptions aren't returned in the same way as return values, they skip up the stack to the first appropriate catch block, so whilst you can't return a value from the constructor you can throw an exception from it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With