Problems with constructors and destructors throwing exceptions

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/fly1988happy/archive/2012/04/11/2442765.html

1. Throwing Exceptions

1.1 Throws an exception (also known as discarding an exception) is the detection of an exception, in C + +, it is implemented with a throw statement, if an exception is detected, throws an exception.

The format of the statement is: throw expression;

If an exception is found in the program segment of the TRY statement block, including the function in which it was called, and the exception is discarded, the exception can be caught and processed by a catch statement after the try statement block, and the condition that is caught and processed is that the type of the thrown exception matches the exception type of the catch statement. Because C + + uses data types to differentiate between different exceptions, the value of the expression in the throw statement has no practical significance when judging the exception, and the type of the expression is particularly important.

1.2 Throwing an exception is actually used as another return value. One of the benefits of throwing exceptions is that the caller has to handle the exception instead of returning an integer-type error code like the previous C language, and the caller tends to ignore it.

1.3 Illustrative examples

If a method is called, call the-->b method to call the-->c method. The throws Exception is then defined in the B and C methods. A try Catch is defined in the A method.

Then when invoking the A method, an exception occurs in the execution to the C method, then the exception is thrown from C to B and then from B to a. A try catch in a will catch the exception, and then you can write your own processing code in the catch.

So why was there an anomaly that was not handled? Because your business logic calls a method, you execute a method, and of course you get an exception in a, and then you deal with it. If the exception is handled in C, it destroys the program structure. In addition, a calls the C method, if it is also called the D,e,f method, if they are likely to throw an exception, you say it is in a to get a good deal, or in the c,d,e,f get the exception, each time to deal with the good? It is also theoretically possible to deal with anomalies at the time, and most of the time, where the exception is handled is based on the needs and the specifics of the project.

2. Constructors can throw exceptions.

3. The C + + standard specifies that destructors cannot, and should not, throw exceptions.

The C + + exception handling model is designed for the C + + language, and further, it is actually serving the object-oriented in the C + + language. The biggest feature and advantage of the C + + exception handling model is the most powerful seamless support for object-oriented C + +. So if an object has an exception during run time, the C + + exception handling model has the responsibility of clearing those objects that have been invalidated because of an exception (that is, the object is out of scope), and releasing the resources originally allocated by the object. This is called the destructor of these objects to complete the task of freeing the resources , so in this sense, the destructor has become part of the exception handling .

The above discussion of C + + exception handling model It actually has a premise hypothesis -- There should be no more exceptions thrown in destructors . Imagine, if the object out of the exception, now the exception processing module in order to maintain the consistency of the system object data, to avoid resource leaks, have the responsibility to release the object's resources, call the object's destructor, but now if the destruction of the process and then the exception, then ask who to ensure that the object of the resource release it? And who is going to deal with this new anomaly? Don't forget that one of the previous exceptions is not finished yet, so it's stuck in a paradox, or infinite recursive nesting. So the C + + standard makes this assumption, of course, this assumption is completely reasonable, in the object construction process, perhaps due to the limited resources of the system resource can not be satisfied, resulting in the occurrence of an exception, but the destructor is completely can be done to avoid abnormal occurrence, after all, you are releasing resources!

What if there is no guarantee that the exception will not occur in the destructor? Although the C + + standard assumes that destructors should not, and never throw exceptions. But the actual software system development is difficult to guarantee this. The execution of all destructors does not occur at all without a single point of exception, which is simply a fantasy, or that you cheat yourself forget it. And sometimes it's easier to refactor an object (freeing a resource) than to construct an object, such as an error in a handle that represents a reference count, which causes the resource to be repeatedly released, and, of course, most of the time it is caused by some logically minor problems with the algorithm the programmer has designed. But don't forget that the current system is so complex that it is impossible to ensure that all programmers write programs that are completely free of bugs. Therefore, it is indeed a bit idealistic to put an end to any exception in the destructor that never happens.

3.1 more effective C + + gives two reasons (destructors cannot throw exceptions):

1) If the destructor throws an exception, the program after the exception point does not execute , and if the destructor performs some necessary actions after the exception point, such as releasing some resources, these actions do not execute and cause problems such as resource leaks.

2) Normally, when an exception occurs, the mechanism of C + + calls the destructor of the constructed object to release the resource, and if the destructor itself throws an exception, the previous exception has not been processed and a new exception has been created, causing the program to crash.

3.2 So what happens when there is no guarantee that an exception will not occur in the destructor?

In fact, there is a good way to solve. That is to completely encapsulate the exception inside the destructor, never let the exception throw out the function. This is a very simple and very effective method.

~classname ()

{

try{

Do_something ();

}

catch () {//You can do nothing here, just make sure the Catch block's program throws an exception that is not thrown out of the destructor .

}

}

3.3 Summary of exceptions thrown in destructors

1) The execution of destructors in C + + should not throw exceptions;

2) If the destructor throws an exception, then your system will become very dangerous, and perhaps a long time what error will not occur, but perhaps your system will sometimes inexplicably collapse and quit, and no signs of it, it is difficult to collapse you all over the ground to find out where the problem appears;

3) When there is some possibility (even a little bit) of an exception in a destructor, then it is necessary to completely encapsulate this possible exception in the destructor, and never let it throw out the function (this trick is simply a lore!). Oh! );

4) Be sure to remember the above summary, the destructor throws an exception causes the program unknown cause of the crash is the fatal internal injury of many systems!

Problems with constructors and destructors throwing exceptions

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.