I know that it\'s not safe to throw exceptions from destructors, but is it ever unsafe to throw exceptions from constructors?
e.g. what happens for objects that ar
As Spence mentioned, throwing from a constructor (or allowing an exception to escape a constructor) risks leaking resources if the constructor is not written carefully to handle that case.
This is one important reason why using RAII objects (like smart pointers) should be favored - they'll automatically handle the cleanup in the face of exceptions.
If you have resources that require deleting or otherwise manually releasing, you need to make certain that they're cleaned up before the exception leaves. This is not always as easy as it might sound (and certainly not as easy as letting an RAII object handle it automatically).
And don't forget, if you need to manually handle clean up for something that happens in the constructor's initialization list, you'll need to use the funky 'function-try-block' syntax:
C::C(int ii, double id)
try
: i(f(ii)), d(id)
{
//constructor function body
}
catch (...)
{
//handles exceptions thrown from the ctor-initializer
//and from the constructor function body
}
Also, remember that exception safety is the main (only??) reason that the 'swap' idiom gained widespread favor - it's an easy way to ensure that copy constructors don't leak or corrupt objects in the face of exceptions.
So, the bottom line is that using exceptions to handle errors in constructors is fine, but it's not necessarily automatic.