Marco A.
Marco A.

Reputation: 43662

Throwing exceptions in destructors - what are the downsides?

What are the downsides of throwing exceptions in destructors?

Right now the only downside I can see is that it might halt freeing resources, are there other downsides to that?

Upvotes: 0

Views: 103

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254411

If the destructor is being called as a result of unwinding the stack to handle another exception, then throwing will terminate the program - you can't have more than one unhandled exception at a time.

If the destructor of an array element throws, then the destructors of the remaining elements won't be called. This could lead to memory leaks and other badness.

Throwing destructors make it difficult or impossible to provide exception guarantees. For example, the "copy-and-swap" idiom used to implement assignment with a strong exception guarantee (i.e. a guarantee that, if an exception is thrown, nothing has been changed) will fail:

thing & thing::operator=(thing const & t) {
    // Copy the argument. If this throws, there are no side-effects.
    thing copy(t);

    // Swap with this. Must have (at least) a strong guarantee
    this->swap(copy);
    // Now the operation is complete, so nothing else must throw.

    // Destroy the copy (now the old value of "this") on return.
    // If this throws, we break the guarantee.
    return *this;
}

Upvotes: 6

Related Questions