从索引外捕获异常
Catching exception from out of index
我有一些主文件,我不能编辑。有一些事情要做,我正在编写适合主文件的类。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类型的异常在无效访问时抛出。
相关文章:
- 当类定义不可见时捕获异常
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 如何通过 pybind11 从 python 中的C++中捕获异常?
- 信号后未捕获异常
- 捕获异常后如何退出程序执行
- C++ 捕获异常后进行清理的标准方法是什么?
- 使用模板类引发和捕获异常
- E/libc++abi:终止于类型为google::protobuf::FatalException的未捕获异常
- 如果在生成 std::thread 后引发,则未捕获异常
- C++ 未捕获异常,程序将终止并中止
- C++程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出适当的值
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
- 为什么捕获异常播放允许尾括号
- throw() 函数应该总是在异常时展开堆栈并允许捕获异常还是必须调用 std::terminate ?
- 寻求与类型为 std::invalid_argument 的未捕获异常相关的运行时错误的建议: stoi:无转换
- 如何从调用函数中捕获异常
- 当用户在字符数组中输入整数值时捕获异常
- C++按值捕获异常时的示例是不好的
- 从索引外捕获异常