Effective C + + Item 08-Don't let exceptions escape destructors

Source: Internet
Author: User

Item 08-Don't let exception escape destructor (Prevent exceptions from leaving destructors)

C + + does not prohibit the destructor from spitting out the exception, but it does not encourage you to do so. There is a reason for that.

Ex:

Class widget{

Public

~widget () {...} Suppose this might spit out an anomaly.

};

void DoSomething ()

{

Std::vector<widget> v;

...//v here to destroy

}

When Vector v is destroyed, it is the responsibility to destroy all the widgets that it contains, assuming that V contains multiple widgets, during which the program may end prematurely or appear ambiguous as long as the destructor spits out the exception.


Workaround:

Ex:

Class dbconn{

Public

~dbconn ()

{

Db.close ();

}

Private

DBConnection DB;

}

If the close call causes an exception, the Dbconn destructor propagates the exception

Workaround:

1. End the program if close throws an exception, usually by calling abort

Dbconn::~dbconn ()

{

Try{db.close;}

catch (...)

{

Make the operation record, write down the call to close failed;

Std::abort ();

}

}

2. Swallow the exception that occurred because of the call to close

Dbconn::~dbconn ()

{

Try{db.close ();}

catch (...)

{

Make a running record and write down the call to close failed

}

}

Better strategy: Redesign the Dbconn interface to give its customers the opportunity to respond to potential problems.


Please remember:

Destructors never spit out an exception; If a function called by a destructor might throw an exception, the destructor should catch any exceptions and swallow them (not propagate) or end the program.

If a customer needs to react to an exception thrown during the operation of an action function, then class should provide a normal function (rather than a destructor) to execute.





Effective C + + Item 08-Don't let exceptions escape destructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.