Item 8: Prevent exceptions from leaving destructors


C++ doesn't prohibit destructors from emitting exceptions, but it certainly discourages the practice. With good reason. Consider:

 class Widget { public:   ...   ~Widget() { ... }            // assume this might emit an exception }; void doSomething() {   std::vector<Widget> v;   ... }                                // v is automatically destroyed here 

When the vector v is destroyed, it is responsible for destroying all the Widgets it contains. Suppose v has ten Widgets in it, and during destruction of the first one, an exception is thrown. The other nine Widgets still have to be destroyed (otherwise any resources they hold would be leaked), so v should invoke their destructors. But suppose that during those calls, a second Widget destructor throws an exception. Now there are two simultaneously active exceptions, and that's one too many for C++. Depending on the precise conditions under which such pairs of simultaneously active exceptions arise, program execution either terminates or yields undefined behavior. In this example, it yields undefined behavior. It would yield equally undefined behavior using any other standard library container (e.g., list, set), any container in TR1 (see Item 54), or even an array. Not that containers or arrays are required to get into trouble. Premature program termination or undefined behavior can result from destructors emitting exceptions even without using containers and arrays. C++ does not like destructors that emit exceptions!

That's easy enough to understand, but what should you do if your destructor needs to perform an operation that may fail by throwing an exception? For example, suppose you're working with a class for database connections:

 class DBConnection { public:   ...   static DBConnection create();        // function to return                                        // DBConnection objects; params                                        // omitted for simplicity   void close();                        // close connection; throw an };                                     // exception if closing fails 

To ensure that clients don't forget to call close on DBConnection objects, a reasonable idea would be to create a resource-managing class for DBConnection that calls close in its destructor. Such resource-managing classes are explored in detail in Chapter 3, but here, it's enough to consider what the destructor for such a class would look like:

 class DBConn {                          // class to manage DBConnection public:                                 // objects   ...   ~DBConn()                            // make sure database connections   {                                     // are always closed    db.close();    } private:   DBConnection db; }; 

That allows clients to program like this:

 {                                       // open a block    DBConn dbc(DBConnection::create());  // create DBConnection object                                         // and turn it over to a DBConn                                         // object to manage  ...                                    // use the DBConnection object                                         // via the DBConn interface }                                       // at end of block, the DBConn                                         // object is destroyed, thus                                         // automatically calling close on                                         // the DBConnection object 

This is fine as long as the call to close succeeds, but if the call yields an exception, DBConn's destructor will propagate that exception, i.e., allow it to leave the destructor. That's a problem, because destructors that throw mean trouble.

There are two primary ways to avoid the trouble. DBConn's destructor could:

  • Terminate the program if close tHRows, typically by calling abort:

     DBConn::~DBConn() {  try { db.close(); }  catch (...) {    make log entry that the call to close failed;    std::abort();  } } 

    This is a reasonable option if the program cannot continue to run after an error is encountered during destruction. It has the advantage that if allowing the exception to propagate from the destructor would lead to undefined behavior, this prevents that from happening. That is, calling abort may forestall undefined behavior.

  • Swallow the exception arising from the call to close:

     DBConn::~DBConn() {  try { db.close(); }  catch (...) {       make log entry that the call to close failed;  } } 

    In general, swallowing exceptions is a bad idea, because it suppresses important information something failed! Sometimes, however, swallowing exceptions is preferable to running the risk of premature program termination or undefined behavior. For this to be a viable option, the program must be able to reliably continue execution even after an error has been encountered and ignored.

Neither of these approaches is especially appealing. The problem with both is that the program has no way to react to the condition that led to close tHRowing an exception in the first place.

A better strategy is to design DBConn's interface so that its clients have an opportunity to react to problems that may arise. For example, DBConn could offer a close function itself, thus giving clients a chance to handle exceptions arising from that operation. It could also keep track of whether its DBConnection had been closed, closing it itself in the destructor if not. That would prevent a connection from leaking. If the call to close were to fail in the DBConnection destructor, however, we'd be back to terminating or swallowing:

 class DBConn { public:   ...   void close()                                     // new function for   {                                                // client use     db.close();     closed = true;   }   ~DBConn()    {    if (!closed) {    try {                                            // close the connection      db.close();                                    // if the client didn't    }    catch (...) {                                    // if closing fails,      make log entry that call to close failed;   // note that and      ...                                             // terminate or swallow    }   } private:   DBConnection db;   bool closed; }; 

Moving the responsibility for calling close from DBConn's destructor to DBConn's client (with DBConn's destructor containing a "backup" call) may strike you as an unscrupulous shift of burden. You might even view it as a violation of Item 18's advice to make interfaces easy to use correctly. In fact, it's neither. If an operation may fail by throwing an exception and there may be a need to handle that exception, the exception has to come from some non-destructor function. That's because destructors that emit exceptions are dangerous, always running the risk of premature program termination or undefined behavior. In this example, telling clients to call close themselves doesn't impose a burden on them; it gives them an opportunity to deal with errors they would otherwise have no chance to react to. If they don't find that opportunity useful (perhaps because they believe that no error will really occur), they can ignore it, relying on DBConn's destructor to call close for them. If an error occurs at that point if close does throw they're in no position to complain if DBConn swallows the exception or terminates the program. After all, they had first crack at dealing with the problem, and they chose not to use it.

Things to Remember

  • Destructors should never emit exceptions. If functions called in a destructor may throw, the destructor should catch any exceptions, then swallow them or terminate the program.

  • If class clients need to be able to react to exceptions thrown during an operation, the class should provide a regular (i.e., non-destructor) function that performs the operation.




Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
Effective C++ Third Edition 55 Specific Ways to Improve Your Programs and Designs
ISBN: 321334876
EAN: N/A
Year: 2006
Pages: 102

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net