Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mitigate exceptions from constructors of aggregated objects if my own constructor must not throw without resorting to "new"?

Tags:

c++

exception

My C++ class aggregates a helper object which may throw an exception in the constructor, but my own class must not throw (my own class is used by a framework which is not prepared for exceptions being thrown by a constructor). Right now I mitigate this risk by delaying the construction of the helper object by creating the object using new so that I'm able to catch any exceptions:

struct HelperObject {
  HelperObject() {
    throw 0;
  }
}

struct MyObject {
  HelperObject *o;
  MyObject() : o( 0 ) {
    try {
      o = new HelperObject;
    } catch ( ... ) {
      // ...
    }
  }
};

However it's a bit annoying to abuse new for this; I suddenly have to deal with a pointer for the entire code for no good reason except that it allows me to get more control over the time at which the object is constructed.

Is it possible to achieve something to this effect without usign new?

like image 445
Frerich Raabe Avatar asked Jan 30 '26 20:01

Frerich Raabe


1 Answers

Could use smart pointer and an extra MakeHelperObject function so that exceptions are done inside HelperObject domain. This only makes MyObject code clean but exception still need to be processed during HelperObject construction:

struct HelperObject {
  HelperObject() {
    throw 0;
  }

   static HelperObject* MakeHelperObject()
   {
     try
     {
       HelperObject* p = new HelperObject();
       return p; 
     }
     catch(const SomeException& e)
     {
      // deal with e
    }
    return NULL;
  }
};


struct MyObject {
  std::unique_ptr<HelperObject> o;
  MyObject() : o(HelperObject::MakeHelperObject())
  {
  }
};
like image 94
billz Avatar answered Feb 01 '26 09:02

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!