| View previous topic :: View next topic |
| Author |
Message |
Jean-Francois Becan Guest
|
Posted: Thu Nov 20, 2003 9:36 am Post subject: exception in constructor |
|
|
Hi,
Is there a mean to throw an exception in a constructor of a C++ class ?
I tried something like that
myClass::myClass()
{
bool bOk = false;
...
if (all works correctly)
{
bOk = true;
}
....
if (!bOk)
{
delete this; // to free the object
throw "Don't work correctly";
}
when I use myClass :
try
{
myClass mine;
...
}
catch(...)
{
// problem with myClass
}
when I compile, I have no problem.
when I run the created soft, if there is a problem in myClass constructor,
the soft becomes completly mad. If I delete the 'throw "Don't work
correctly";' line, the soft doesn't lose his head.
Has someone succeeded in throwing exception in constructor ?
Is there an example how to make this work ?
Thanks
|
|
| Back to top |
|
 |
Ivan Johansen Guest
|
Posted: Thu Nov 20, 2003 12:56 pm Post subject: Re: exception in constructor |
|
|
Jean-Francois Becan wrote:
| Quote: | delete this; // to free the object
|
You cannot delete an object that is not fully constructed. Remove this
line at it should work.
Ivan Johansen
|
|
| Back to top |
|
 |
Jean-Francois Becan Guest
|
Posted: Thu Nov 20, 2003 3:34 pm Post subject: Re: exception in constructor |
|
|
"Ivan Johansen" <NG5 (AT) Padowan (DOT) remove.dk> a écrit dans le message de
news:3fbcb9c8 (AT) newsgroups (DOT) borland.com...
| Quote: | Jean-Francois Becan wrote:
delete this; // to free the object
You cannot delete an object that is not fully constructed. Remove this
line at it should work.
Ivan Johansen
|
Thanks
In this case, where is the object deleted ?
Jean-Francois Becan
|
|
| Back to top |
|
 |
Remy Lebeau (TeamB) Guest
|
Posted: Thu Nov 20, 2003 6:34 pm Post subject: Re: exception in constructor |
|
|
"Jean-Francois Becan" <jfbecan (AT) jouve (DOT) fr> wrote
| Quote: | Is there a mean to throw an exception in a constructor of a C++ class ?
|
The same way you throw any exception in general - use the 'throw' keyword.
| Quote: | delete this; // to free the object
throw "Don't work correctly";
|
*Do not* call delete like that! If a constructor throws an exception, the
object will automatically be freed. Never try to free the object manually
like that. Just throw the exception and let the language handle the rest
for you:
myClass::myClass()
{
...
if (!bOk)
throw "Don't work correctly";
}
Gambit
|
|
| Back to top |
|
 |
Remy Lebeau (TeamB) Guest
|
Posted: Thu Nov 20, 2003 6:34 pm Post subject: Re: exception in constructor |
|
|
"Jean-Francois Becan" <jfbecan (AT) jouve (DOT) fr> wrote
| Quote: | In this case, where is the object deleted ?
|
The C++ language itself frees the partially-constructed object automatically
if its constructor throws an exception.
Gambit
|
|
| Back to top |
|
 |
|