Re: Exceptions & Constructors
<jalqadir@gmail.com> wrote in message
news:1185794153.322347.136860@l70g2000hse.googlegroups.com...
The constructor in MyClass instantiates many objects pointers through
'new', I would like to implement a way to make sure that the object
has been allocated in memory by catch(ing) the bad_alloc exception
error, but this means that I have to throw this error back from
MyClass constructor, how can I avoid this?
Well, what do you want your code to do on failure?
Consider:
class Foo
{
// ...
};
int main()
{
Foo Bar;
}
What do you want to happen if Bar can not be instantized because of bad
allocation inside of Foo's constructor? And how do you want to check if it
was successful?
Some things I can think of off the top of my head.
1. Have Foo contain a private bool variable stating if all pointers have
been instantized correctly with newed instances. Alternative to this, is to
check any of the pointers itself for a NULL value which you would set in the
constructor if initializaiton of the variables failed. Foo could have a
method returning if it was initalized or not. Foo could have it's internal
methods checking initialzation.
2. Have Foo created only by a factory (I.E returning a pointer). If Foo can
not be instantized, the factory returns NULL which mainline can check.
3. Do nothing and have new's throw propogate up to mainline
I could think of a few other methods depending on what you would want done.
It is not a good thing to have an instance floating around that was not
properly instantized. How are you going to provent this if you don't allow
new's throw to propogate? How do you WANT to prevent it?