Throwing exception in construcutor

If a constructor of an object throws an exception, does the object get created?
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() {

and then call the following code,

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

The resulting error is a null pointer exception indicating the class was not created.
Constructors cannot throw exception.
Ripon070400Author Commented:
This is not true, Constructors of classes can throw exceptions (apologies for object)
For example
public Integer (String s) throws NumberFormatException
You need to remember that any static variables changed in the constructor before the exception is thrown will change value.
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.