Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what happens when evaluating the arguments of a constructor call throws an exception?

Tags:

java

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);
    }
}
like image 416
Lancel Avatar asked Mar 05 '16 17:03

Lancel


1 Answers

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.

like image 50
user207421 Avatar answered Oct 14 '22 12:10

user207421