2.9.2. Runtime Errors

Programs that contain runtime errors compile but "crash" or fail to end when they run. Runtime errors are more difficult to locate than either syntax or logical errors. Fortunately, none of the programming operations that we have studied so far are likely to cause a runtime error. In fact, with our current knowledge of C++, it's difficult to demonstrate a runtime error by causing one. Nevertheless, our discussion of errors is not complete without some mention of runtime errors.

We can more easily address runtime errors with a debugger, and later chapters will amplify the techniques illustrated here and in the previous section. For now, we take a simple approach that also lays a foundation that will help us understand how the debugger locates runtime errors.

cerr << "Running statement 1-3" << endl;
statement 1;
statement 2;
statement 3;
cerr << "Statement 1-3 done" << endl;
	.
	.
	.
statement n;
int function()
{
	cerr << "Entering function" << endl;
	statement 1;
	statement 2;
		. . .
	statement n;
	cerr << "Exiting function" << endl;
}
(a)(b)
Locating runtime errors. Imagine that a program exhibits a runtime error. The program likely consists of many statements, so which statement is causing the error?
  1. Programmers may suspect one of several statements. They surround the suspect statements with instrumenting code.
  2. If an entire function is suspect, programmers put instrumenting statements at its beginning and end.
Keep moving the two output statements closer together. As long as the program (1) continues to exhibit the runtime error and (2) only produces output from the first output statement, we know the failing statement lies between the two output statements. The idea is to narrow our attention to just one or two statements that can cause the error. When the error is localized, it is easier to recognize and correct.

A debugger automates and simplifies this localization process, and it has the advantage that we don't need to remove any instrumenting code when we finish debugging this error. The process is the as described above, but we replace the instrumenting (cerr) statements with debugger tracepoints (see Examining Statements With Tracepoints in the previous section). Moving the trace points together identifies the failing statement.