Solved

Throwing exception in construcutor

Posted on 2001-09-07
4
268 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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 85
rhino JavaScript import, load 25 84
How to convert String matching to regex in java 4 33
Chrome and Firefox Java 5 34
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
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…

810 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