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

后端 未结 4 479
感情败类
感情败类 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: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.
    

提交回复
热议问题