Solved

Throwing exception in construcutor

Posted on 2001-09-07
4
288 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This video teaches viewers about errors in exception handling.

688 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