O'Reilly logo

Safe C++ by Vladimir Kushnir

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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());\ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required