C++ – When and how to use exceptions

Original link:When and How to Use Exceptions

In this article, I will present a clear and practical answer to the question "When, for what, and how should you use exceptions instead of error codes to report errors?", an answer that builds on previous research (see "References").

Over the years, I've often heard the advice: "Use exceptions in exceptional circumstances." But I've also often pointed out that, while this advice is well-intentioned, it's clichéd and unsatisfying in practice, neither clear nor explicit - it's as good as saying it. Why? The main problem is that "exceptions" are neither objective nor measurable, which means that it just leaves us with the exact same set of questions we started with, only rephrased from "When and for what should I use exceptions?" to "Okay, so what are 'exceptions'?"

In order to come up with a legible and unambiguous normative answer, we must determine three things:

  • We need a rigorous, objective, and measurable definition of what constitutes an error. We also need guidance on where to report and handle them.
  • We need clear and understandable safety guarantees that describe error handling.
  • Finally, we need to understand which errors should be reported and handled using exceptions.

For the first two points, I will not discuss exceptions specifically at all, but will discuss error handling and safety guarantees. This is to highlight and emphasize that exceptions are just one of several equivalent mechanisms we can choose to use for reporting and handling errors. Only in the last part will I return to discussing exceptions specifically and hopefully explain convincingly why you should use exceptions instead of error codes whenever possible, and point out a few cases where exceptions cannot be used.

Distinguishing between errors and non-errors

A function is a unit of work, and failures should be classified as errors or non-errors based on the effect they have on the function. f If and only if the failure is due to the function f The caller of the function does not meet any of its preconditions, f It cannot satisfy any of its postconditions, or cannot re-establish the function f It is an error if a function fails to maintain any invariants that it is responsible for maintaining. In particular, I am not considering programming errors here, which is a separate category that is usually handled using assertions.

Before we can properly think about the specific error handling methods and specifications, it is important to clearly distinguish between errors and non-errors based on the impact of the error on the function. The key words in this section are Preconditions , Postcondition 和 Invariants .

Functions are the fundamental unit of work, whether you are writing C++ in a structured, object-oriented, or generic style. A function makes assumptions about its starting state, called preconditions, which are the responsibility of the caller, and performs one or more actions, called return values ​​or postconditions, which are the responsibility of the callee. Functions may also be collectively responsible for maintaining one or more invariants. In particular, non-const member functions are units of work defined on an object that always transform the object from one valid state that preserves invariants to another valid state. Within the body of a member function, an object's invariants can and almost always must be broken, and this is normal, as long as they are reestablished at the end of the member function. In addition, higher-level functions group lower-level functions into larger units of work.

An error is any failure that prevents a function from succeeding. Thus, there are three main kinds of errors:

  • This causes the function's preconditions to fail, such as not meeting parameter restrictions.
  • This causes the postcondition of the function to fail to meet. For example, when the function has a return value, a valid return value cannot be established.
  • Causing a function to fail to reestablish the invariants it is responsible for maintaining is a special type of postcondition that applies particularly well to member functions. A fundamental postcondition of every non-private member function is that it must reestablish the invariants of its class. (See [Stroustrup00] E.2.)

Any other condition is not an error and should not be reported as such.

The code that may cause the error is responsible for detecting and reporting the error. In particular, this means that the caller should be responsible for detecting and reporting the preconditions of the called function. If the caller fails to do this, it is a programming error, so when a precondition violation is detected within the called function, it can be handled using assertions.

Consider some examples:

  • std::string::insert – Try to be in a specific location pos When inserting new characters into a string,pos The value of is out of bounds which violates the precondition on the parameters, since there is no valid starting point, the function cannot successfully perform its work, so it is a precondition error.

  • std::string::append – When appending characters to a string, if the existing buffer is full and allocating a new buffer fails, this prevents the function from performing its functionality and satisfying its postcondition, and is therefore a postcondition error.

  • Unable to generate return value – For functions that return a value, generating a valid return value is a postcondition. If the return value cannot be created correctly, for example, if the function returns a floating point number but no floating point value exists with the required mathematical properties, this is a postcondition error.

  • std::string::find_first_of – When searching for a character in a string, failure to find the character is a legitimate result, not an error. At least, it is not an error as far as the generic string class is concerned, and if the owner of a given string assumes that a character will be present, and its absence results in a violation of higher-level invariants, then the higher-level calling code should appropriately report an error about its invariants.

A function should report an error when it detects an error that it cannot handle itself and that prevents it from operating normally or as expected in any way. Handle the error where there is enough context to handle the error, convert the error, or enforce the boundaries defined in the error policy, such as in main and thread mainline.

Now that we have a clear definition of what an error is and when to report and handle it, what guarantees can and should we provide for robust error reporting and handling?

Providing safety in functions

  • Basic guarantee – Make sure errors always leave your program in a valid state. Beware of errors that break invariants.

  • Strong Guarantee – Additional guarantee that the final state is either the original state, i.e. the operation is rolled back in case of errors, or the expected target state.

  • No-failure guarantee – Makes an additional guarantee that the operation will never fail. While this is not possible for most functions, it is required for some functions such as destructors, deallocation functions, and swap functions.

The basic, strong, and no-failure guarantees were originally described in [Abrahams96] and publicized in [GotW], [Stroustrup00] E.2, and [Sutter00] with respect to exception safety, but they apply to all error handling, regardless of the specific approach used, so I will use them to describe general error handling safety.

The strong guarantee is a strict superset of the basic guarantee, and the no-failure guarantee is a strict superset of the strong guarantee. In general, each function should provide the strongest guarantee it can, without unnecessarily penalizing calling code that does not need that guarantee, and, where possible, provide enough functionality to allow calling code that needs the stronger guarantee to implement it, see vector::insert Example.

Ideally, we should write functions that always succeed and therefore provide a guarantee that they will not fail. And some functions must always provide a guarantee that they will not fail, notably destructors, deallocation functions, and swap functions.

However, most functions can fail. When errors are likely to occur, the safest approach is to ensure that the function has transactional behavior, that is, either it succeeds completely and takes the program from one valid state to another, or it fails and leaves the program in the same state as before the call, that is, any objects visible before the failed call are the same as after the failed call, such as global variables. int The value will not be changed from 42 become 43 , this is a strong guarantee.

Finally, if providing strong guarantees is difficult or involves unnecessary overhead, then provide a basic guarantee, i.e. either the function succeeds completely and reaches the expected target state, or it does not succeed completely and leaves the program in a valid state, i.e. maintaining invariants that the function is aware of and responsible for maintaining, but which is unpredictable, i.e. it may or may not be the original state, and may or may not satisfy some of the postconditions, but note that all invariants must still be reestablished. The application must be designed to handle this state appropriately.

As it stands, there is no lower level of guarantee. Failure to meet the basic guarantees is always a programming error. Correct programs should provide at least the basic guarantees for all functions, even the rare correct programs that intentionally leak resources by design, because even in the case of an immediate program termination, it is known that these resources will be reclaimed by the operating system. Resources are always guaranteed to be correctly released in the presence of errors, and data is left in a consistent state, unless the error is so severe that graceful or ungraceful termination is the only option.

  • Retry after failure – If your program includes commands that save data to files, when a write fails, make sure to recover to a state where the user can retry the operation. An editor that does not allow the name of the file to be saved to be changed after a write error is metastable. In particular, do not free any data structures until the data has been safely flushed to disk.

  • skin – If you write a skinnable application, do not destroy the existing skin before trying to load a new one. This prevents your application from being left in an unusable state if loading the new skin fails.

  • std::vector::insert - because std::vector The internal storage of is contiguous, and inserting an element into the middle requires moving some existing values ​​to the next position to make room for the new element. Move operations use T::operator= If the operation may throw an exception, then std::vector::insert The only way to provide strong guarantees is to make a complete copy of the container, perform the operation on the copy, and if successful, use the non-failed std::vector::swap Swap the original and the copy. But if each std::vector::insert If everyone does this, then std::vector::insert Implementations of always have the space and time overhead of constructing a full copy of the container, whether or not the strong guarantees are needed. This is an unnecessary penalty. Instead, callers that do want the strong guarantees can do the work themselves.

  • Retracting a launched rocket – Consider a function f , as part of launching a rocket, and FireRocket The function provides a strong guarantee or a guarantee that it will not fail. f can perform all the work that could fail before launching the rocket, then it can be coded to provide strong guarantees. But if it must perform other operations that could fail after it has already launched the rocket, then it cannot provide strong guarantees because it cannot retrieve the rocket. In any case, such f This should probably be split into two functions, as a single function probably shouldn't try to do multiple such important jobs, it's better to give one function a coherent responsibility.

Now we have the two key pieces in hand, a clear definition of what an error is and when to report and handle it, and what guarantees we can and should provide for robust error reporting and handling. We can now move on to the key question of the final piece, when should we use exceptions instead of other techniques, especially error codes, to report errors?

Prefer exceptions to report errors

Prefer exceptions to error codes for reporting errors. Use status codes to report errors only when exceptions cannot be used, that is, when you do not control all possible user code and cannot guarantee that it is written in C++ and compiled with the same compiler and compatible compilation options so that exception handling works, and for conditions that are not errors. In particular, when recovery is not necessary or possible, other methods such as graceful or ungraceful termination can be used.

It's no coincidence that most modern languages ​​created in the last 20 years use exceptions as their primary or only error reporting mechanism.

By definition, an exception is used to report an exception to normal processing, that is, an "error". In the first section we defined it as a violation of a precondition, postcondition, and invariant. We use the term "status code" to cover all forms of reporting status through a code, including return codes, errno , GetLastError and similar strategies by return value or check code, and specifically use "error code" to refer to those status codes that indicate an error.

In C++, reporting errors via exceptions has significant advantages over reporting via error codes, including making your code more robust.

  • Exceptions cannot be silently ignored – The most terrible weakness of error codes is that they can be ignored by default. To add sanity to error codes, you must explicitly write code to accept errors and respond to them. It is common for programmers to ignore error codes accidentally or lazily. This makes code review more difficult. Exceptions cannot be silently ignored. If you ignore an exception, you must explicitly catch it, even if it is just catch(...) and choose not to act on it.

  • Automatic exception propagation – Error codes are not propagated by default. To notify higher-level functions of the error codes of lower-level functions, programmers who write intermediate code must explicitly write error propagation code by hand. Exceptions are automatically propagated by default until the error is handled, which directly supports good error handling, that is, "It is not a good idea to try to make every function a firewall. The best error handling strategy is to handle non-local errors only on the designated primary interface." —— [Stroustrup94] 16.8

  • Exceptions remove error handling and recovery from the main line of control flow – When error detection and handling are written, they are necessarily intertwined with the main line of control flow. This makes both the main control flow and the error handling code more difficult to understand and maintain. Exception handling naturally moves error detection and recovery into different catch blocks, that is, it makes error handling explicitly modular rather than inline spaghetti code. This makes the main line of control easier to understand and maintain, and the clear distinction between correct action and error detection and recovery has more than just aesthetic benefits.

  • Exception handling is better than other methods for reporting errors in constructors and operators – In most cases, constructors and operators have predefined signatures and do not reserve space for returning error codes. In particular, constructors may not have a return type at all, not even void , and each operator+ Must take exactly two arguments and return an object. For operators, using error codes is possible but not ideal, and requires something like errno or a suboptimal solution such as packaging the state with the object. Using error codes for constructors is not feasible because the C++ language tightly binds constructor exceptions and constructor failures so that the two must be synonymous. If we use something like errno Methods.

    FSomeType Object;  // 构造一个对象
    if (FSomeType::ConstructionWasOK()) {
        // 测试构造是否成功
    }
    // ...

    The result is not only difficult to use and error-prone, but can also lead to the construction of erroneous objects that exist but do not actually satisfy the class invariants, not to mention the fact that they are not useful in multithreaded applications. FSomeType::ConstructionWasOK There is an inherent race condition in calling . (See [Stroustrup00] E.3.5)

The main potential disadvantage of exception handling is that it requires the programmer to be familiar with some recursive idioms that arise from the extra control flow of exceptions. For example, destructors and deallocation functions must not throw exceptions, and intermediate code must be correct in the face of exceptions. To achieve the latter, a common coding idiom is to safely perform all work that might throw exceptions on the copy, and then only when you know that the actual work has succeeded can you commit and modify the program state using only non-throwing operations. But using error codes also has its own idiom, it's just that it has been around longer, so more people already know about them, but unfortunately, people also often and routinely ignore them. Caveat emptor.

Performance is not usually a disadvantage of exception handling. First, note that you should always turn exception handling on, even if it is turned off by default in your compiler, because otherwise you will not get the standard behavior and error reporting from the C++ language and standard library. When turning on compiler support for exception handling, this may result in an increase in the size of the executable image, which is partially unavoidable, but in normal processing, that is, when no errors have occurred, the performance difference between throwing exceptions and returning error codes is usually negligible. In the case of errors, you may notice a performance difference, but if you throw so often that the performance overhead of exception throwing and catching is very obvious, it is almost certain that you are using exceptions for things that are not real errors and are therefore not distinguishing between errors and non-errors correctly, see Section 1. If they are true violations of preconditions, postconditions, and invariants, and they do occur, then you will not be able to use them.ThenIf it happens frequently, then there is something more serious wrong with the application.

One symptom of overuse of error codes is application code that constantly needs to check for trivial, always-true conditions, or worse, fails to check error codes that should be checked.

One symptom of overuse of exceptions is that application code throws and catches exceptions so frequently that catch The execution frequency of the block is almost the same as try For example, when trying to execute try During the block, more than 10% of the attempts will result in an exception being thrown. catch Either the block is not actually handling real errors, i.e. violations of preconditions, postconditions, or invariants, or there is something more serious wrong with the program.

See, for example, Section 1 and the two examples below.

  • Constructor - If a constructor cannot successfully create an object of its type, which is equivalent to failing to establish all the invariants of the new object, it should throw an exception. In contrast, an exception thrown from a constructor always means that the construction of the object failed and the object's life cycle never began. The language enforces this.

  • Successful recursive search – When using a recursive search algorithm, you might be tempted to return results and conveniently unwind the search stack by throwing them as exceptions. But exceptions mean errors, and finding a result is not an error. Also, in the context of a search function, not finding a result is not an error, see find_first_of Example.

In rare cases, when you know the following conditions.

  • The benefits of exception do not apply - For example, you know that the immediate caller almost always has to handle errors directly, and propagating errors should never or almost never happen. This is very rare, because usually the callee does not have so much information about all caller peculiarities.

  • Performance differences do matter - For example, the performance difference is measured empirically, so you might want to throw an exception in a loop. This is again very rare, as it usually means that the failure isn't actually a bug at all, but let's assume it is.

Consider using error codes.

Final Thoughts

Distinguish between errors and non-errors. A failure is an error if and only if it causes a function to fail to satisfy a precondition for which it was called, to establish its own postconditions, or to reestablish an invariant that it is collectively responsible for maintaining. Everything else is not an error.

Making sure errors always leave your program in a valid state is fundamental. Beware of errors that break invariants.

It is best to additionally guarantee that the final state is either the original state, that is, the operation is rolled back when there is an error, or the expected target state, which is a strong guarantee.

It would be nice to have an extra guarantee that the operation will never fail. While this is not possible for most functions, it is necessary for functions such as destructors and deallocation functions.

Finally, prefer exceptions to error codes for reporting errors. Use error codes only when exceptions are not an option, that is, when you do not control all possible user code and cannot guarantee that it is written in C++ and compiled with the same compiler and compatible compilation options, and for failures that are not errors.

Thanks

Thanks to Dave Abrahams, Andrei Alexandrescu, Scott Meyers, and Bjarne Stroustrup for their comments and contributions to this article. This article is excerpted from the new book "C++ Coding Standards" co-authored by this author, Herb Sutter, and Andrei Alexandrescu, which will be published in October 2004.

References

  1. [Abrahams96] D. Abrahams. "Exception Safety in STLport" (STLport web site, 2001). Available online at http://www.stlport.org/doc/exception_safety.html.
  2. [Abrahams01] D. Abrahams. "Error and Exception Handling" (Boost web site, 2001). Available online at http://www.boost.org/more/error_handling.html.
  3. [Alexandrescu03] A. Alexandrescu and D. Held. "Smart Pointers Reloaded" (C/C++ Users Journal, 21(10), October 2003). Available at http://www.moderncppdesign.com/publications/cuj-10-2003.html.
  4. [Stroustrup94] B. Stroustrup. The Design and Evolution of C++ (Addison-Wesley, 1994).
  5. [Stroustrup00] B. Stroustrup. The C++ Programming Language, Special Edition (Addison-Wesley, 2000). Note in particular the exception safety appendix, also available online at http://www.research.att.com/~bs/3rd_safe0.html.
  6. [SuttAlex05] H. Sutter and A. Alexandrescu. C++ Coding Standards (available in October 2004; Addison-Wesley, 2005).
  7. [Sutter00] H. Sutter. Exceptional C++ (Addison-Wesley, 2000), Items 8-19, 40, 41, and 47.
  8. [Sutter02] H. Sutter. More Exceptional C++ (Addison-Wesley, 2002), Items 17-23.
  9. [Sutter04] H. Sutter. Exceptional C++ Style (available in August 2004; Addison-Wesley, 2004), Items 11, 12, and 13.

One thought on "C++ – When and how to use exceptions"

Post Reply