bobby car

C++ Core Guidelines: Rules for Error Handling

Error handling is an essential part of writing good software; therefore, the C++ core guidelines have about 20 rules for error handling.

bobby car

 First of all. Which aspects are involved in error handling according to the guidelines:

  • Detecting an error
  • Transmitting information about an error to some handler code
  • Preserve the state of a program in a valid state
  • Avoid resource leaks

You should use exceptions for error handling. David Abrahams, one of the founders of the Boost C++ Library and former member of the ISO C++ standardization committee, formalized in the document “Exception-Safety in Generic Components” what exception-safety means. His Abrahams Guarantees describe a fundamental contract if you think about exception-safety; therefore, I will mention them here in short and refer to them in the upcoming post. Here are the four levels of the contract from the already mentioned wiki page in decreasing order:

  1. No-throw guarantee, also known as failure transparency: Operations are guaranteed to succeed and satisfy all requirements, even in exceptional situations. If an exception occurs, it will be handled internally and not observed by clients.
  2. Strong exception safety, also known as commit or rollback semantics: Operations can fail, but failed operations are guaranteed to have no side effects, so all data retain their original values.
  3. Basic exception safety, also known as a no-leak guarantee: Partial execution of failed operations can cause side effects. All invariants are preserved, and no resource leaks (including memory leaks) exist. Any stored data will contain valid values, even if they differ from before the exception.
  4. No exception safety: No guarantees are made.

Often, you can not fully recover from an error. Now, you have two options.

First, let the program run in a simpler error state. This means the software is not fully functional anymore but provides at least reduced functionality. For example, it may not be possible for a defibrillator to apply the power but you can at least guide the operator.

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    Or, second, restart the program. Often, this is the fastest and the easiest way to get into a safe state, recover, and get fully functional. 

    The rules from the guidelines should help you to avoid the following kinds of errors:

    • Type violations
    • Resource leaks
    • Bounds errors
    • Lifetime errors
    • Logical errors
    • Interface errors

    After my more general remarks, let me start with the first three rules:

    E.1: Develop an error-handling strategy early in a design

    The entire rule consists only of this reason. “A consistent and complete strategy for handling errors and resource leaks is hard to retrofit into a system.” That is too little for an explanation. Error handling is a so-called cross-cutting concern such as logging or security. This means these concerns are challenging to address because they can not be easily modularized. They affect the entire software.

    Exception safety is an integral part of the interface design and has to be, therefore, addressed from the first beginning. Now the question is: What is an interface? My definition of an interface is quite broad.

    An interface is a protocol between two components. One component may be a function, an object, a sub-system, or the entire system. This component may also be an external dependency, such as hardware or an operating system.

    You have two ways to communicate at the boundary level: regularly and irregularly. Regular communication is the functional aspect of the interface. Or, to say it differently: What the system should do. Irregular communication stands for the non-functional aspects. The non-functional aspect specifies how a system should perform. A big part of the non-functional aspects is exception-handling or what can go wrong. Often the non-functional aspects are just called quality attributes.

    From a general point of view, an interface consists of two components. Each component has to fulfill a special kind of contract.

    1. A Precondition that must always hold before a component is called.
    2. An Invariant must always be true during the execution of the component.
    3. A Postcondition that must always be true after the execution of the component.

    These terms go back Bertrand Meyer and are known as design by contract.

     

     Design by contract

     

    By FabuioOwn work, CC0, Link

    Before I continue, I should mention that we may get contracts with C++20.

    E.2: Throw an exception to signal that a function can’t perform its assigned task

    The consequence of this rule is that the caller of the function should handle the exception with a try/catch statement. The critical question is: When should you throw an exception? Here are typical use cases:

    • A precondition that cannot be met
    • A constructor that cannot construct an object
    • An out-of-range error
    • The inability to acquire a resource 

    E.3: Use exceptions for error handling only

    This is, in my opinion, one of the worst misuses of exceptions. Exceptions are a kind of goto statement. Maybe your code guidelines forbid you to use goto statements. Therefore, you devised a clever idea: use exceptions for control flow. In the following example, the exception is used in the success case.

    // don't: exception not used for error handling
    int find_index(vector<string>& vec, const string& x)
    {
        try {
            for (gsl::index i = 0; i < vec.size(); ++i)
                if (vec[i] == x) throw i;  // found x
        } catch (int i) {
            return i;
        }
        return -1;   // not found
    }
    

     

    The code snippet uses gsl::index from the guideline support library. In this case, the regular control flow is not separated from the exceptional control flow. In the success case, the code uses a throw statement; in the failure case, the code uses a return statement. If that is not confusing?

    What’s next?

    Of course, I will continue with the rules for error handling in the next post. In particular, I write about preconditions, postconditions, and invariants.

     

     

     

    Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    Standard Seminars (English/German)

    Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

    • C++ – The Core Language
    • C++ – The Standard Library
    • C++ – Compact
    • C++11 and C++14
    • Concurrency with Modern C++
    • Design Pattern and Architectural Pattern with C++
    • Embedded Programming with Modern C++
    • Generic Programming (Templates) with C++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *