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 retains 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 less 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. The regular communication is the functional aspect of the interface. Or to say it differently: What the system should do. The 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 to error handling. In particular, I write about precondition, postcondition, and invariants.

 

 

 

Thanks a lot to my Patreon Supporters: Eric Pederson, Paul Baxter,  Meeting C++, Matt Braun, Avi Lachmish, Adrian Muntea, and Roman Postanciuc.

 

 

Get your e-book at leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more the 100 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 600 pages full of modern C++ and more than 100 source files presenting concurrency in practice.

 

Add comment


Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 2718

All 1164698

Currently are 227 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments