从索引外捕获异常

Catching exception from out of index

本文关键字:捕获异常 索引      更新时间:2023-10-16

我有一些主文件,我不能编辑。有一些事情要做,我正在编写适合主文件的类。V1对象是我自己的vector类的一个实例。

在main的某个点,我有这一行。

try {
    // trying to get the element at(4)
    // should give an error
    cout << v1[4] << endl;
} catch (const string & err_msg) {
    cout << err_msg << endl;
}

我的v1向量的大小是"3",所以程序崩溃,因为我的索引。在这里犯错误是可以的。但是我怎样才能在程序崩溃之前得到一个异常呢?我不允许编辑主代码。我需要对头文件或类定义做一些事情。谢谢。

在不修改主代码的情况下,您应该编写自己的矢量类来检查operator[]中的边界。

类似:

template <typename T>
class MyVector
{
  T *data;
  int length;
  ...
  T &operator[](int i)
  {
    if (i < 0 || i >= length)
       throw std::string("Out of bounds!"); //throw std::out_of_range;
    else
       return data[i];
  }
  ...
};

如果你使用std::vector,你可以使用at代替[]:

返回对指定位置(pos. Bounds)的元素的引用执行检查,将出现std::out_of_range类型的异常在无效访问时抛出。