Consider the simple example in Java below. What happens if I create an object by calling new B(0)
? First, an object of type B in created in memory. Then, the expression 1/n will throw an exception. But the created object will never become finalized according to the Java spec (§12.6.1) below. 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).
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.
So there is no memory leak.
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