Jeffrey Chen
Jeffrey Chen

Reputation: 237

Exception-Handling C++

How do I do this,

I have a class called LargeInteger that stores a number of maxmimum 20 digits. I made the constructor

LargeInteger::LargeInteger(string number){ init(number); }

Now if the number is > LargeInteger::MAX_DIGITS (static const member) i.e 20 i want to not create the object and throw an exception.

I created an class LargeIntegerException{ ... }; and did this

void init(string number) throw(LargeIntegerException);
void LargeInteger::init(string number) throw(LargeIntegerException)
{
    if(number.length > MAX_DIGITS)
    throw LargeIntegerException(LargeIntegerException::OUT_OF_BOUNDS);
    else ......
}

So now i modified the constructor

LargeInteger::LargeInteger(string number)
{ try {init(number);} catch(LargeIntegerExceptione) {...} }

Now I have 2 questions
1.Will the object of this class be created incase an exception is thrown?
2.How to handle it if the above is true?

Upvotes: 0

Views: 155

Answers (2)

jmucchiello
jmucchiello

Reputation: 18984

There is no reason to catch the exception in the constructor. You want the constructor to fail so something outside the constructor has to catch it. If a constructor exits via exception, no object is created.

LargeInteger(string num) { init(num); } // this is just fine.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258678

No, if an exception is thrown in the constructor, the object is not constructed (provided you don't catch it, like you do).

So - don't catch the exception, rather let it propagate to the calling context.

IMO, this is the right approach - if the object can't be initialize directly, throw an exception in the constructor and don't create the object.

Upvotes: 4

Related Questions