Solved

Throwing exception in construcutor

Posted on 2001-09-07
4
258 Views
Last Modified: 2006-11-17
If a constructor of an object throws an exception, does the object get created?
0
Comment
Question by:Ripon070400
  • 2
4 Comments
 
LVL 2

Expert Comment

by:sateesh_babu
ID: 6464108
Constructors cannot throw exception.
0
 

Author Comment

by:Ripon070400
ID: 6464149
This is not true, Constructors of classes can throw exceptions (apologies for object)
For example
public Integer (String s) throws NumberFormatException
0
 

Accepted Solution

by:
erikjensen earned 50 total points
ID: 6464277
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
 

Expert Comment

by:erikjensen
ID: 6464320
You need to remember that any static variables changed in the constructor before the exception is thrown will change value.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
scoresSpecial  challenge 13 40
Receive file in Servlet 1 36
triangle challenge 4 77
create a gui in perl 3 42
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This video teaches viewers about errors in exception handling.

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now