Re: is such exception handling approach good?

Tech-Archive recommends: Speed Up your PC by fixing your registry



On Sat, 22 Dec 2007 16:11:04 -0500, "Larry Smith"
<no_spam@xxxxxxxxxxx> wrote:

it is normally not a good idea to do operations in the ctor that could
cause an exception. the reason for this is that if an exception is
ever thrown in your ctor you end up with an invalid object. therefore
it is better to have some other method to initialize such with and
handle a failure outside the ctor like bool init() or something.

That's completely false as Alex stated.


i forgot to add: the dtor is never called when ctor throws an
exception so the heck do you do the cleanup if the ctor has allocated
three different things?

please tell me since you obviously have such insight.

The canonical example:

class MyClass
{
public:
MyClass() : m_Whatever(new Whatever)
{
// m_Whatever's destructor is still called
throw SomeException();
}
private:
std::auto_ptr<Whatever> m_Whatever;
};


so your requirement is that all member variables must be smart
pointers? not that great.
.



Relevant Pages

  • Re: is such exception handling approach good?
    ... same time, the construction of m_Whatever is successful, but the construction ... of current instance is failed and exception is thrown -- throw ... if the caller of the constructor MyClass() is smart enough, ... handle a failure outside the ctor like bool initor something. ...
    (microsoft.public.vc.language)
  • Re: is such exception handling approach good?
    ... cause an exception. ... ever thrown in your ctor you end up with an invalid ... There is nothing wrong with throwing from constructor. ... won't end up with invalid object. ...
    (microsoft.public.vc.language)
  • Re: Exception-safe constructors
    ... > for the field a and b in class bidon should be called after the ... > exception is thrown in the constructor; ...
    (comp.lang.cpp)
  • Re: CArray
    ... About the copy ctor: I used to think that, if no copy ctor is explicitly ... the compiler provides a default one which does member-wise copy. ... Even if I wonder about the exception system... ... So, if your STL container class throws an exception, this exception is not ...
    (microsoft.public.vc.language)
  • Re: is such exception handling approach good?
    ... the reason for this is that if an exception is ... ever thrown in your ctor you end up with an invalid object. ... handle a failure outside the ctor like bool initor something. ... it can't refer to members http://www.gotw.ca/gotw/066.htm ...
    (microsoft.public.vc.language)