Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Exception thrown in constructor, can my object still be created?

Could you tell me can be some case when exception is throwing in constructor and object is not null. I mean some part of object is created and another is not.Like this

public Test(){
name = "John";
// exception
// init some other data.
}

I understand in this sitiation object Test will be null, but Can be situation that object test cannot be null (delete block of exception not answer :) ) ?

like image 757
jitm Avatar asked May 06 '11 10:05

jitm


1 Answers

A class instance creation expression always creates a new object if the evaluation of its qualifier and arguments complete normally, and if there is space enough to create the object. It doesn't matter if the constructor throws an exception; an object is still created. The class instance creation expression does not complete normally in this case, though, as it propagates the exception.

However, you can still obtain a reference to the new object. Consider the following:

public class C {
    static C obj; // stores a "partially constructed" object
    C() {
        C.obj = this;
        throw new RuntimeException();
    }
    public static void main(String[] args) {
        C obj;
        try {
            obj = new C();
        } catch (RuntimeException e) {
            /* ignore */
        }
        System.out.println(C.obj);
    }
}

Here, a reference to the new object is stored elsewhere before the exception is thrown. If you run this program, you will see that the object is indeed not null, though its constructor did not complete normally.

like image 141
Nathan Ryan Avatar answered Sep 20 '22 18:09

Nathan Ryan