异常out_of_range

使用C++容器类访问成员时由于使用问题可能会遇到 terminate called after throwing an instance of ‘std::out_of_range’”或者”Abort message: ‘terminating with uncaught exception of type std::out_of_range

原因如下:

  • 索引超出容器范围
  • 容器为空,在尝试访问一个空容器的元素时,也会触发此异常,因为容器中没有任何元素可供访问。
  • 错误的索引计算

我们可以使用std::out_of_range捕获这个异常

1
2
3
4
5
6
7
8
9
10
11
12
vector<int>  vec;
vec.push_back(1);
vec.push_back(2);

try
{
cout<< vec.at(vec.size() ) <<endl;
}
catch (const std::out_of_range& err)
{
std::cerr << "\nOut of range error:" << err.what()<< endl;
}