1.6 Error Handling
“An error doesn’t become a mistake until you refuse to correct it.”
—Orlando Aloysius Battista
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 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 this:
assert_test: assert_test.cpp:10: double square_root(double): Assertion 'result >= 0.0' failed.
The assertion requires that our result must be greater than or equal to zero; otherwise 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 activate -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 not impossible), 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. If there are so many properties to check that the actual functionality is no longer clearly visible in the code, the tests can be outsourced to 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 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 even more work than the actual task. In such cases, it is usually more efficient trying to accomplish the task and checking for Exceptions along the way.
1.6.2.1 Motivation
Before illustrating the old-style error handling, we introduce our anti-hero Herbert11 who is an ingenious mathematician and considers programming a necessary evil for demonstrating how magnificently his algorithms work. He 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, matrix& A) { fstream f(fname); if (!f.is_open()) return 1; ... return 0; }
So, he 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 his return code? Nothing! The program keeps going and might crash later on absurd data, or even worse might 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 reasoning across to programming dinosaurs like Herbert might not convince them: “Not only are you dumb enough to pass in a nonexisting file to my perfectly implemented function, then you do not even check the return code. You do everything wrong, not me.”
C++17 We get a little bit more security with C++17. It introduces the attribute [[nodiscard]] to state that the return value should not be discarded:
[[nodiscard]] int read_matrix_file(const char* fname, matrix& A)
As a consequence, each call that ignores the return value will cause a warning, and with an additional compiler flag we can turn each warning into an error. Conversely, we can also suppress this warning with another compiler flag. Thus, the attribute doesn’t guarantee us that the return code is used. Furthermore, merely storing the return value into a variable already counts as usage, regardless of whether we touch this variable ever again.
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. So much for messing around with error codes. Let us now see how exceptions work.
1.6.2.2 Throwing
The better approach to deal with problems is to throw an exception:
matrix read_matrix_file(const std::string& fname) { fstream f(fname); if (!f.is_open()) throw "Cannot open file."; ... }
C++ allows us to throw everything as an exception: strings, numbers, user types, et cetera. However, for dealing with the exceptions properly it is better to define exception types or to use those from the standard library:
struct cannot_open_file {}; matrix read_matrix_file(const std::string& fname) { fstream f(fname); if (!f.is_open()) throw cannot_open_file{}; matrix A; // populate A with data (possibly throw exception) return A; }
Here, we introduced our own exception type. In Chapter 2, we will explain in detail how classes can be defined. In the preceding example, we defined an empty class that only requires opening and closing braces followed by a semicolon. Larger projects usually establish an entire hierarchy of exception types that are usually 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. In our example we threw an exception for a file we were unable to open, which we can catch now:
try { A= read_matrix_file("does_not_exist.dat"); } catch (const cannot_open_file& e) { // Here we can deal with it, hopefully. }
We can write multiple catch clauses in the block to deal with different exception types in one location. Discussing this in detail makes much more sense after introducing classes and inheritance. Therefore we postpone it to Section 6.1.5.
1.6.2.4 Handling Exceptions
The easiest handling is delegating it to the caller. This is achieved by doing nothing (i.e., no try-catch-block).
We can also catch the exception, provide an informative error message, and terminate the program:
try { A= read_matrix_file ("does_not_exist.dat"); } catch (const 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 (const cannot_open_file& e) { cerr ≪ "O my gosh, the file is not there! Please caller help me.\n"; throw; }
In our case, we are already in the main function and there is no other function on the call stack to catch our exception. Ignoring an exception is easily implemented by an empty block:
} catch (cannot_open_file&) {} // File is rubbish, don't care
So far, our exception handling did not really solve our problem of missing a file. If the filename is provided by a user, we can pester him/her until we get one that makes us happy:
bool keep_trying= true; do { std::string fname; cout ≪ "Please enter the filename: "; cin ≫ fname; try { A= read_matrix_file(fname); ... keep_trying= false; } catch (const cannot_open_file& e) { cout ≪ "Could not open the file. Try another one!\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.
1.6.2.5 Advantages of Exceptions
Error handling is necessary when our program runs into a problem that cannot be solved where it is detected (otherwise we’d do so, obviously). Thus, we must communicate this to the calling function with the hope that the detected problem can be solved or at least treated in a manner that is acceptable to the user. It is possible that the direct caller of the problem-detecting function is not able to handle the either, and the issue must be communicated further up the call stack over several functions, possibly up to the main function. By taking this into consideration, exceptions have the following advantages over error codes:
Function interfaces are clearer.
Returning results instead of error codes allows for nesting function calls.
Untreated errors immediately abandon the application instead of silently continuing with corrupt data.
Exceptions are automatically propagated up the call stack.
The explicit communication of error codes obfuscates the program structure.
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.
C++11 1.6.2.6 Who Throws?
C++03 allowed specifying which types of exceptions can be thrown from a function. Without going into details, these specifications turned out not to be very useful and were deprecated since C++11 and removed since C++17.
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.5 and leave it to you when you read it.
C++11 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.
static_assert(sizeof(int) >= 4, "int is too small on this platform for 70000"); const int capacity= 70000;
In this example, we store the literal value 70000 to an int. Before we do this, we verify that the size of int is large enough on the platform this code snippet is compiled for to hold the value correctly. The complete power of static_assert is unleashed with meta-programming (Chapter 5) and we will show more examples there.