Constructor fail?

  • Thread starter Thread starter xxxxyz
  • Start date Start date
X

xxxxyz

Hi,

I want to create a class with a constructor which can fail (for example
if (..) fail;). When constructor fail I want the variable to point to
null. Example:

class PosInt{
int i;
public PosInt(int j)
{
if (j<0)
?fail?;
i=j;
}
}

.....

PosInt m=new PosInt(-5); //after this I want m=null

How can I do this (What to put instead ?fail?)? Is this a good practice
and style?

Thanks.
 
The ability to fail a constructor is often done by throwing an exception in
the constructor. However, this is not good because AFAIK it can result in
incorrect clean-ups of the partially created object. Instead, use the
Factory Pattern to create the class.
 
Sean Hederman said:
The ability to fail a constructor is often done by throwing an exception in
the constructor. However, this is not good because AFAIK it can result in
incorrect clean-ups of the partially created object.

Only if the constructor isn't coded properly - if it can fail, it
should dispose of anything which needs disposing of before it throws
the exception. It won't result in any memory leaks or anything like
that though.
Instead, use the Factory Pattern to create the class.

If you want to return null rather than throwing an exception, this is
the only course, yes.
 
Jon Skeet said:
Only if the constructor isn't coded properly - if it can fail, it
should dispose of anything which needs disposing of before it throws
the exception. It won't result in any memory leaks or anything like
that though.

Okay, I thought that there were some issues with throwing exceptions in
constructors. Obviously I was wrong. Thanks for the correction Jon.
 
Back
Top