Class DBConnection {public:... static DBConnection create (); // This function returns the DBConnection object void close (); // closes the connection. If the connection fails, an exception is thrown };
A better policy is to create a DBConn class used to manage DBConnection resources. The DBConn class provides a close function, which gives the customer a chance to handle "exceptions caused by this operation ". DBConn can also track whether the managed DBConnection has been closed. If it has not been closed, it is disabled by the DBConn destructor. This prevents lost data connections. However, if the DBConnection destructor fails to call close, you can use the "Force end program" or "Swallow exception" method:
Class DBConn {public: DBConn ();~ DBConn (); void close (); private: DBConnection db; bool closed;}; DBConn: DBConn () {} DBConn ::~ DBConn () {if (! Closed) {try {db. close (); // close the connection} catch (...) // If the close action fails {write log, write down the call to close failed; // record and end the program... // or swallow an exception;} void DBConn: close () // The new function {db. close (); closed = true ;}