C++ Core Guidelines: Rules for Error Handling

Contents[Show]

Error handling is an important part of writing good software; therefore, the C++ core guidelines has 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++ standardisation committee, formalised in the document "Exception-Safety in Generic Components" what exception-safety means. His Abrahams Guarantees describe a contract that is fundamental if you think about exception-safety; therefore, I will mention them here in short and will 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, but all invariants are preserved and there are no resource leaks (including memory leaks). Any stored data will contain valid values, even if they differ from what they were 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 a reduced functionality. For example, it may not be possible for a defibrillator to apply the power but you can at least guide the operator.

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." To be honest, 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 difficult to address because they can not be easily modularised. They affect the entire software.

Exception safety is an important 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.

At the boundary level, you have two way to communicate: 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 fulfil a special kind of contract.

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

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

 

 Design by contract

 

By Fabuio - Own 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 key 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 statements. Maybe your code guidelines forbid you to use goto statements. Therefore, you came up with a totally 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 continue in the next post with the rules for error handling. In particular, I write about precondition, postcondition, and invariants.

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Satish Vangipuram, and Michael Dunsky.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, and Said Mert Turkal.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

Seminars

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

Bookable (Online)

German

Standard Seminars (English/German)

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

New

Contact Me

Modernes C++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 4855

Yesterday 6789

Week 48620

Month 209294

All 6857986

Currently are 174 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments