In Java, what happens when evaluating constructor invocation arguments throws an exception?

Consider a simple example in Java below. What happens if I create an object by calling new B(0) ? Firstly, an object of type B created in memory. Then the expression 1 / n throws an exception. But the created object will never be completed according to the Java specification (ยง12.6.1) below. So will there be a memory leak?

Please note that I am not asking: "Can the constructor throw an exception", but "what happens if the constructor throws an exception in a specific situation".

Object o is not refined until its constructor calls the constructor for the object by o and this call does not succeed (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); } } 
+8
java
source share
1 answer

The section you quote distinguishes between reachability and finality:

Each object can be characterized by two attributes :. It may be available, the finalizer is reachable, or unavailable, and it may also not be finalized, finalizable, or completed.

Thus, an object may be accessible or inaccessible, and may also be definitively defined or not definitively defined.

In case you mention, then the constructor Object never starts, so the object is not finalizable, but the Oto constructor threw an exception so the new concession never results in a variable, so this is unattainable.

Therefore, there is no memory leak.

+4
source share

All Articles