7.6. A run-time error

Way back in Section [run-time] I talked about run-time errors, which are errors that don’t appear until a program has started running.

So far, you probably haven’t seen many run-time errors, because we haven’t been doing many things that can cause one. Well, now we are. If you use the at() function and you provide an index that is negative or greater than length-1, you will get a run-time error and a message something like this:

index out of range: 6, string: banana

Try it in your development environment and see how it looks.

Running the active code below will result in a runtime error. Can you fix it so that we print out the first letter and last letter of string greeting instead of indexing out of range?

Note

Range-checked access vs. Unchecked access

In the C++ Standard Library, the [] operator does not check the index value provided. The [] operator will never generate a runtime error, even if the value is clearly impossible:

int mydata[3] = {1,2,3};
cout << mydata[-99];

Containers that provide an at() function provide a range-checked alternative to the [] operator. the [] operator and you provide an index that is negative or greater than length-1, you will get a run-time error and a message something like this:

Construct a block of code that correctly changes the string to say “cat in the hat” instead of “cat on the mat”, then print it.

You have attempted of activities on this page