Chapter 3. What to Do When We Encounter an Error at Runtime

There are two types of runtime errors: those that are the result of programmer error (that is, bugs) and those that would happen even if the code were absolutely correct. An example of the second type occurs when a user mistypes a username or password. Other examples occur when the program needs to open a file, but the file is missing or the program doesn’t have permission to open it, or the program tries to access the Internet but the connection doesn’t work. In short, even if the program is perfect, things such as wrong inputs and hardware issues can produce problems.

In this book we concentrate on catching run-time errors of the first type, a.k.a. bugs. A piece of code written for the specific purpose of catching bugs will be called a sanity check. When a sanity check fails, i.e., a bug is discovered, this should do two things:

  1. Provide as much information as possible about the error, i.e., where it has occurred and why, including all values of the relevant variables.

  2. Take an appropriate action.

What is an appropriate action? We’ll discuss this later in more detail, but the shortest answer is to terminate the program. First, let’s concentrate on the information about the bug, called the error message. To diagnose a bug we provide a macro defined in the scpp_assert.hpp file:

#define SCPP_ASSERT(condition, msg) \ if(!(condition)) { \ std::ostringstream s; \ s << msg; \ SCPP_AssertErrorHandler( \ __FILE__, __LINE__, s.str().c_str());\ ...

Get Safe C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.