C++ string.at() Out-of-Range Exception Example
The given C++ program demonstrates the use of the string.at() method and how to handle the out_of_range exception it can throw.
#include <string>
#include <iostream>
using namespace std;
int main() {
string s = 'Hello';
try {
s.at(5);
} catch (out_of_range & e) {
cerr << e.what() << endl;
}
return 0;
}
The program tries to access the character at index 5 in the string s, which is 'Hello'. Since the string has only 5 characters (indexed from 0 to 4), this causes an out_of_range exception.
The catch block handles the exception, and the code prints the error message generated by the exception, which is:
'basic_string::at: __n (which is 5) >= this->size() (which is 5)'
This message indicates that the attempted access at index 5 is out of bounds because the string's size is 5. The program then continues execution normally.
原文地址: https://www.cveoy.top/t/topic/lcW 著作权归作者所有。请勿转载和采集!