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);
}
}