?
Solved

Throwing exception in construcutor

Posted on 2001-09-07
4
Medium Priority
?
292 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 200 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

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…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month10 days, 22 hours left to enroll

770 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