0

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so where do i catch the exception then ?
@JeffreyChen wherever you call the constructor.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.