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

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

提交回复
热议问题