Throwing exception in construcutor

If a constructor of an object throws an exception, does the object get created?
Ripon070400Asked:
Who is Participating?
 
erikjensenConnect With a Mentor Commented:
When an Exception is thrown from a constructor the object is not created, try this,

create the following class,

class test {
   public int count;
         
    public test() throws Exception {
        throw new Exception("test");
    }
         
    public void inc() {
        count++;
    }
}

and then call the following code,

test testObj = null;
try{
    testObj = new test();
}catch(Exception e){}
         
testObj.inc();  //Error

The resulting error is a null pointer exception indicating the class was not created.
0
 
sateesh_babuCommented:
Constructors cannot throw exception.
0
 
Ripon070400Author Commented:
This is not true, Constructors of classes can throw exceptions (apologies for object)
For example
public Integer (String s) throws NumberFormatException
0
 
erikjensenCommented:
You need to remember that any static variables changed in the constructor before the exception is thrown will change value.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.