构造函数中的异常 [英] Exceptions in constructors
问题描述
在C ++中,当构造函数成功完成时,对象的生命周期就会开始。在构造函数中,对象不存在。
问:从构造函数中引发异常是什么意思? b
$ bA:这意味着施工失败,物体永远不存在,其生命从未开始。 [来源]
我的问题是:Java是否同样适用?例如,如果我将这个
转到另一个对象,然后我的构造函数失败?
Foo()
{
Bar.remember(this);
throw new IllegalStateException();
}
这个定义很好吗?
该对象存在,但没有被正确初始化。
每当这个
在施工过程中泄漏(不只是当你抛出一个例外)
这是一个非常有问题的情况,因为一些常见的保证在这种情况下不成立(例如
因此,您绝对应该避免泄漏这个
在构造函数中。
IBM developerWorks文章介绍了构建对象时采取的预防措施以及这些预防措施背后的推理。虽然本文根据多线程讨论了这个问题,但在单线程环境中,当未知/不受信任的代码在构建期间引用此
时,您可能会遇到类似的问题。
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 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.
这篇关于构造函数中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!