Error handling is an essential part of writing good software; therefore, the C++ core guidelines have about 20 rules for error handling.
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:
- 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.
- 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.
- 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.
- 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.
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
- E.2: Throw an exception to signal that a function can’t perform its assigned task
- E.3: Use exceptions for error handling only
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.
- A Precondition that must always hold before a component is called.
- An Invariant must always be true during the execution of the component.
- A Postcondition that must always be true after the execution of the component.
Before I continue, I should mention that we may get contracts with C++20.
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
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.
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?
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, Matthieu Bolt, 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, and Marco Parri Empoli.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
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++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,