EC notes, Part Two: 8. Don't let exceptions escape destructors

Source: Internet
Author: User

1. Why should destructors not throw exceptions?
There are two types of situations:
1). If there are many statements in the destructor, and the first statement throws an exception (or other statement), then the statement after the exception is thrown is not executed. What we usually write in the destructor is the code that cleans up the resource (or reclaims the resource), and then some of the resources are not recycled, causing the memory leak or the program to end prematurely (abort).
2). The time at which the destructor was called was when the object was destroyed, and it was difficult to know (or not deliberately notice) when the object was destroyed, so it was difficult to catch an exception thrown by the destructor (let alone deal with it).
2. Two not a smart solution
1). Catch the exception in the destructor and terminate the program
2). Catch an exception in the destructor and swallow the exception
Both of these approaches solve the second case (the terminating program will no longer be thrown), but the first case is still difficult to solve
3. A better solution
By passing the work of the destructor to the other member functions to pass the exception, and doing exception handling in the member function, the destructor simply checks to see if the resource is successfully cleaned up, and if it is not cleaned successfully, then the destructor is cleaned up (the destructor handles the exception in 2 ways), and the exception is guaranteed not to be propagated. So if the cleanup work of the member function executes successfully, then everything is OK, and if it is not executed successfully, go back to the origin and the destructor handles the exception. Double Insurance

EC notes, Part Two: 8. 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.