Exceptions: Exceptions in Constructors

OverviewHow Do IFAQ

When throwing an exception in a constructor, clean up whatever objects and memory allocations you have made prior to throwing the exception, as explained in Exceptions: Throwing Exceptions from Your Own Functions.

Throwing an exception in a constructor is tricky, however, because the memory for the object itself has already been allocated by the time the constructor is called. There is no simple way to deallocate the memory occupied by the object from within the constructor for that object. Thus, you will find that throwing an exception in a constructor will result in the object remaining allocated. For a discussion of how to detect objects in your program that have not been deallocated, see the article Diagnostics: Detecting Memory Leaks.

If you are performing operations in your constructor that can fail, it might be a better idea to put those operations into a separate initialization function rather than throwing an exception in the constructor. That way, you can safely construct the object and get a valid pointer to it. Then you can call the initialization function for the object. If the initialization function fails, you can delete the object directly.

For more information, see Exceptions: Freeing Objects in Exceptions.