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.

The at() member function checks its index. If the index is greater than or equal to the string's size(), it throws std::out_of_range. A negative argument is converted to an unsigned index and is also out of range. If the exception is not caught, the program terminates; the exact error message depends on your development environment.

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?

Example runtime_error_AC_1
1#include <iostream>
2#include <string>
3
4int main() {
5    std::string greeting = "Hello world";
6    std::cout << "The first letter is " << greeting.at(-1) << '\n';
7    std::cout << "The last letter is " << greeting.at(greeting.length()) << '\n';
8}

Note

Range-checked access vs. unchecked access

In C++20, array indexing and the [] operators of std::string and std::vector do not provide the range checks performed by at(). An invalid unchecked access can cause undefined behavior: the program might crash, produce unexpected results, or appear to work. You cannot rely on either an error message or successful execution.

For example, mydata[-99] is invalid for int mydata[3] = {1, 2, 3};. Use a valid index regardless of whether a particular run reports an error.

String indexing has one special case: reading text[text.size()] yields the terminating null character, not a character of the string's contents. To visit the characters, use indices strictly less than text.size(). In contrast, text.at(text.size()) throws an exception.

Q1

Click on each out-of-range access. Consider each expression independently.


    
    char a = 
    char b = 
    char c = 
    char d = 
    
    cout <<    << '\n';
    char e = 
    cout <<    << '\n';
}

Q2

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.

  1. cout << sentence << '\n';
  2. int main() {
  3. sentence [12] = 'h'; #distractor
  4. sentence[11] = 'h' #distractor
  5. sentence[11] = 'h';
  6. sentence[3] = 'i'; #distractor
  7. sentence[4] = 'i';
  8. sentence[5] = 'i'; #distractor
  9. string sentence = "cat on the mat";
  10. }