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

后端 未结 4 473
感情败类
感情败类 2020-12-16 18:31

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

相关标签:
4条回答
  • 2020-12-16 18:43

    No. Look at the client code:

    Test myObj = null;
    try {
     myObj = new Test();
    } catch(MyException e) {
      System.out.println("" + myObj);
    }
    

    Here, when exception occurs, the '=' operation is not executed. Your code goes straight to the catch block and myObj stays null.

    0 讨论(0)
  • 2020-12-16 18:44

    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.

    0 讨论(0)
  • 2020-12-16 18:58

    No. If exception occurs during the instantiation of the object, it will not be created.

    Anyway, you would you write it?

    MyObject obj = new MyObject();
    // This code will not be reachable in case of an Exception
    

    or:

    MyObject obj = null;
    try {
        obj = new MyObject();
    } catch (AnyException e) {
    }
    // Here, either obj is created correctly, or is null as an Exception occurred.
    
    0 讨论(0)
  • 2020-12-16 19:05
    public Test() {  
        name = "John"; 
        try {
            // exception 
    
            // init some other data.
        } catch(AnyException e) {
            // catch
        }
    }
    

    The above code makes sense as per your expectation.

    0 讨论(0)
提交回复
热议问题