There is a lot of controversy about the anomalies in C + +, but it is often an untrue misunderstanding. Exception was once a difficult language feature, fortunately, with the C + + community experience accumulated, today we have enough knowledge to easily write the exception of safe code, and the writing of abnormal security code generally does not affect performance.
Use an exception or return an error code? This is a vexed topic. You must have heard the saying that exceptions are used only when they are truly abnormal. So what's the "real anomaly"? Before answering this question, let's take a look at the principle of invariant in program design.
object is the attribute aggregation plus method, how to determine whether an object's attribute aggregation is logically correct state? This can be done through a series of assertions, the last of which concludes that the attribute aggregation of this object is logically correct or problematic. These assertions are the invariant expressions that measure the object's attribute aggregation to error.
We usually implement an invariant check in a function call. The invariant type is divided into three kinds: former condition, after condition and invariant type. Pre-condition refers to the logical condition that must be met before the function is called, and the following condition is the logical condition that must be satisfied after the function is called, and the invariant is the condition that must be met in the execution of the function. In our discussion, the invariant is both a former condition and a later condition. The former condition must be satisfied, if not satisfied, that is the program logic error, after the condition is not necessarily. Now, we can use the invariant to strictly define the abnormal condition: meet the former conditions, but can not meet the conditions, that is, abnormal conditions. Throws an exception if and only if an exception condition occurs.
The return value reporting error is not rejected in the answer to when an exception is thrown, and the two are orthogonal. However, as far as our experience is concerned, it is entirely possible to choose between the two. In fact, when we make this choice, it necessarily means that the meaning of the interface changes, without changing the interface of the case, in fact, can not be selected (try to use the return value to handle errors in the constructor). Through the invariant to distinguish between normal and abnormal conditions, but also better to refine the interface.