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) |
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.