[英]In Java, what happens when evaluating the arguments of a constructor call throws an exception?
Consider the simple example in Java below. 考虑下面的Java中的简单示例。 What happens if I create an object by calling
new B(0)
? 如果通过调用
new B(0)
创建对象会怎样? First, an object of type B in created in memory. 首先,在内存中创建类型为B的对象。 Then, the expression 1/n will throw an exception.
然后,表达式1 / n将引发异常。 But the created object will never become finalized according to the Java spec (§12.6.1) below.
但是,根据以下Java规范(第12.6.1节),创建的对象将永远不会完成。 So do we get a memory leak?
那么我们会发生内存泄漏吗?
Please note that I am not asking "can a constructor throw an exception", but "what happens if a constructor throws an exception in a particular situation." 请注意,我并不是在问“构造函数是否可以引发异常”,而是“如果构造函数在特定情况下引发异常会发生什么”。
An object o is not finalizable until its constructor has invoked the constructor for Object on o and that invocation has completed successfully (that is, without throwing an exception).
在对象o的构造函数调用了o上的Object的构造函数并且该调用成功完成(即没有引发异常)之后,该对象o才能终结。
class A {
int n;
A(int n) {
this.n = n;
}
}
class B extends A {
B(int n) {
super(1/n);
}
}
The section you're quoting distinguishes between reachability and finalizability: 您引用的部分区分可达性和可终结性:
Every object can be characterized by two attributes: it may be reachable, finalizer-reachable, or unreachable, and it may also be unfinalized, finalizable, or finalized.
每个对象都可以通过两个属性来表征:它可以是可达的,终结器可达的或不可达的,也可以是未终结的,终结的或终结的。
So an object can be reachable or unreachable, and finalizable or not finalizable, independently. 因此,一个对象可以独立地可到达或不可到达,并且可以终结或不可终结。
In the case you mention, the Object
constructor has never run, so the object isn't finalizable, but OTOH the constructor has thrown an exception so the assignment of the new
result to a variable never happens, so it is unreachable. 在您提到的情况下,
Object
构造函数从未运行过,因此该对象无法最终确定,但是OTOH构造函数抛出了异常,因此从未发生将new
结果分配给变量的情况,因此无法实现。
So there is no memory leak. 因此,没有内存泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.