1.6 Error Handling
- “An error doesn’t become a mistake until you refuse to correct it.”
- —John F. Kennedy
The two principal ways to deal with unexpected behavior in C++ are assertions and exceptions. The former is intended for detecting programming errors and the latter for exceptional situations that prevent proper continuation of the program. To be honest, the distinction is not always obvious.
1.6.1 Assertions
The macro assert from header <cassert> is inherited from C but still useful. It evaluates an expression, and when the result is false then the program is terminated immediately. It should be used to detect programming errors. Say we implement a cool algorithm computing a square root of a non-negative real number. Then we know from mathematics that the result is non-negative. Otherwise something is wrong in our calculation:
#include <cassert>
double square_root(double x)
{
check_somehow(x >= 0);
...
assert(result >= 0.0);
return result;
}
How to implement the initial check is left open for the moment. When our result is negative, the program execution will print an error like
assert_test: assert_test.cpp:10: double square_root(double):
Assertion 'result >= 0.0' failed.
The fact is when our result is less than zero, our implementation contains a bug and we must fix it before we use this function for serious applications.
After we fixed the bug we might be tempted to remove the assertion(s). We should not do so. Maybe one day we will change the implementation; then we still have all our sanity tests working. Actually, assertions on post-conditions are somehow like mini-unit tests.
A great advantage of assert is that we can let it disappear entirely by a simple macro declaration. Before including <cassert> we can define NDEBUG:
#define NDEBUG
#include <cassert>
and all assertions are disabled; i.e., they do not cause any operation in the executable. Instead of changing our program sources each time we switch between debug and release mode, it is better and cleaner to declare NDEBUG in the compiler flags (usually -D on Linux and /D on Windows):
g++ my_app.cpp -o my_app -O3 -DNDEBUG
Software with assertions in critical kernels can be slowed down by a factor of two or more when the assertions are not disabled in the release mode. Good build systems like CMake include -DNDEBUG automatically in the release mode’s compile flags.
Since assertions can be disabled so easily, we should follow this advice:
Even if you are sure that a property obviously holds for your implementation, write an assertion. Sometimes the system does not behave precisely as we assumed, or the compiler might be buggy (extremely rare but possible), or we did something slightly different from what we intended originally. No matter how much we reason and how carefully we implement, sooner or later one assertion may be raised. In the case that there are so many properties that the actual functionality gets cluttered by the tests, one can outsource the tests into another function.
Responsible programmers implement large sets of tests. Nonetheless, this is no guarantee that the program works under all circumstances. An application can run for years like a charm and one day it crashes. In this situation, we can run the application in debug mode with all the assertions enabled, and in most cases they will be a great help to find the reason for the crash. However, this requires that the crashing situation is reproducible and that the program in slower debug mode reaches the critical section in reasonable time.
1.6.2 Exceptions
In the preceding section, we looked at how assertions help us to detect programming errors. However, there are many critical situations that we cannot prevent even with the smartest programming, like files that we need to read but which are deleted. Or our program needs more memory than is available on the actual machine. Other problems are preventable in theory but the practical effort is disproportionally high, e.g., to check whether a matrix is regular is feasible but might be as much or more work than the actual task. In such cases, it is usually more efficient to try to accomplish the task and check for Exceptions along the way.
1.6.2.1 Motivation
Before illustrating the old-style error handling, we introduce our anti-hero Herbert8 who is an ingenious mathematician and considers programming a necessary evil for demonstrating how magnificently his algorithms work. He learned to program like a real man and is immune to the newfangled nonsense of modern programming.
His favorite approach to deal with computational problems is to return an error code (like the main function does). Say we want to read a matrix from a file and check whether the file is really there. If not, we return an error code of 1:
int read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if (!f.is_open())
return 1;
...
return 0;
}
So, we checked for everything that can go wrong and informed the caller with the appropriate error code. This is fine when the caller evaluated the error and reacted appropriately. But what happens when the caller simply ignores our return code? Nothing! The program keeps going and might crash later on absurd data or even worse produce nonsensical results that careless people might use to build cars or planes. Of course, car and plane builders are not that careless, but in more realistic software even careful people cannot have an eye on each tiny detail.
Nonetheless, bringing this point across to programming dinosaurs like Herbert might not convince them: “Not only are you dumb enough to pass in a non-existing file to my perfectly implemented function, then you do not even check the return code. You do everything wrong, not me.”
Another disadvantage of the error codes is that we cannot return our computational results and have to pass them as reference arguments. This prevents us from building expressions with the result. The other way around is to return the result and pass the error code as a (referred) function argument which is not much less cumbersome.
1.6.2.2 Throwing
The better approach is to throw an exception:
matrix read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if (!f.is_open())
throw "Cannot open file.";
...
}
In this version, we throw an exception. The calling application is now obliged to react on it—otherwise the program crashes.
The advantage of exception handling over error codes is that we only need to bother with a problem where we can handle it. For instance, in the function that called read_matrix_file it might not be possible to deal with a non-existing file. In this case, the code is implemented as there is no exception thrown. So, we do not need to obfuscate our program with returning error codes. In the case of an exception, it is passed up to the appropriate exception handling. In our scenario, this handling might be contained in the GUI where a new file is requested from the user. Thus, exceptions lead at the same time to more readable sources and more reliable error handling.
C++ allows us to throw everything as an exception: strings, numbers, user types, et cetera. However, to deal with the exceptions properly it is better to define exception types or to use those from the standard library:
struct cannot_open_file {};
void read_matrix_file(const char* fname, ...)
{
fstream f(fname);
if(!f.is_open())
throw cannot_open_file{};
...
}
Here, we introduced our own exception type. In Chapter 2, we will explain in detail how classes can be defined. In the example above, we defined an empty class that only requires opening and closing brackets followed by a semicolon. Larger projects usually establish an entire hierarchy of exception types that are often derived (Chapter 6) from std::exception.
1.6.2.3 Catching
To react to an exception, we have to catch it. This is done in a try-catch-block:
try {
...
} catch (e1_type& e1)
{ ...
} catch (e2_type& e2) { ... }
Wherever we expect a problem that we can solve (or at least do something about), we open a try-block. After the closing braces, we can catch exceptions and start a rescue depending on the type of the exception and possibly on its value. It is recommended to catch exceptions by reference [45, Topic 73], especially when polymorphic types (Definition 6–1 in §6.1.3) are involved. When an exception is thrown, the first catch-block with a matching type is executed. Further catch-blocks of the same type (or sub-types; §6.1.1) are ignored. A catch-block with an ellipsis, i.e., three dots literally, catches all exceptions:
try { ...
} catch (e1_type& e1) { ... }
catch (e2_type& e2) { ... }
catch (...) { // deal with all other exceptions
}
Obviously, the catch-all handler should be the last one.
If nothing else, we can catch the exception to provide an informative error message before terminating the program:
try {
A= read_matrix_file("does_not_exist.dat");
} catch (cannot_open_file& e) {
cerr ≪ "Hey guys, your file does not exist! I'm out.\n";
exit(EXIT_FAILURE);
}
Once the exception is caught, the problem is considered to be solved and the execution continues after the catch-block(s). To terminate the execution, we used exit from the header <cstdlib>. The function exit ends the execution even when we are not in the main function. It should only be used when further execution is too dangerous and there is no hope that the calling functions have any cure for the exception either.
Alternatively we can continue after the complaint or a partial rescue action by rethrowing the exception which might be dealt with later:
try {
A= read_matrix_file("does_not_exist.dat");
} catch (cannot_open_file& e) {
cerr ≪ "O my gosh, the file is not there! Please caller help me.\n";
throw e;
}
In our case, we are already in the main function and there is nothing else on the call stack to catch our exception. For rethrowing the current one, there exists a shorter notation:
} catch (cannot_open_file&) {
...
throw;
}
This shortcut is preferred since it is less error-prone and shows more clearly that we rethrow the original exception. Ignoring an exception is easily implemented by an empty block:
} catch (cannot_open_file&) {} // File is rubbish, keep going
So far, our exception handling did not really solve our problem of missing a file. If the file name is provided by a user, we can pester him/her until we get one that makes us happy:
bool keep_trying= true;
do {
char fname[80]; // std::string is better
cout ≪ "Please enter the file name: ";
cin ≫ fname;
try {
A= read_matrix_file(fname);
...
keep_trying= false;
} catch (cannot_open_file& e) {
cout ≪ "Could not open the file. Try another one!\n";
} catch (...)
cout ≪ "Something is fishy here. Try another file!\n";
}
} while (keep_trying);
When we reach the end of the try-block, we know that no exception was thrown and we can call it a day. Otherwise, we land in one of the catch-blocks and keep_trying remains true.
A great advantage of exceptions is that issues that cannot be handled in the context where they are detected can be postponed for later. An example from the author’s practice concerned an LU factorization. It cannot be computed for a singular matrix. There is nothing we can do about it. However, in the case that the factorization was part of an iterative computation, we were able to continue the iteration somehow without that factorization. Although this would be possible with traditional error handling as well, exceptions allow us to implement it much more readably and elegantly. We can program the factorization for the regular case and when we detect the singularity, we throw an exception. Then it is up to the caller how to deal with the singularity in the respective context—if possible.
1.6.2.4 Who Throws?
Already C++03 allowed specifying which types of exceptions can be thrown from a function. Without going into details, these specifications turned out to be not very useful and are deprecated now.
C++11 added a new qualification for specifying that no exceptions must be thrown out of the function, e.g.:
double square_root(double x) noexcept { ... }
The benefit of this qualification is that the calling code never needs to check for thrown exceptions after square_root. If an exception is thrown despite the qualification, the program is terminated.
In templated functions, it can depend on the argument type(s) whether an exception is thrown. To handle this properly, noexcept can depend on a compile-time condition; see Section 5.2.2.
Whether an assertion or an exception is preferable is not an easy question and we have no short answer to it. The question will probably not bother you now. We therefore postpone the discussion to Section A.2.6 and leave it to you when you read it.
1.6.3 Static Assertions
Program errors that can already be detected during compilation can raise a static_assert. In this case, an error message is emitted and the compilation stopped. An example would not make sense at this point and we postpone it till Section 5.2.5.