std::out_of_range异常奇怪的输出
std::out_of_range exception weird output
所以我在模板类中有这个函数:
T getValue(int x, int y) const throw(logic_error, out_of_range) { // value getter
try {
if (x > rows || y > cols || x <= 0 || y <= 0)
throw out_of_range("Invalid x or y.");
else
return data[cols*(x-1)+(y-1)];
} catch (out_of_range& e) {
cerr << e.what() << endl;
}
}
如果我尝试给它一个超出范围的数字,则异常有效,但输出始终为:
Invalid x or y.
1
我已经尝试了一个小时来弄清楚那个 1 是从哪里来的,我到底错过了什么?这当然与std::out_of_range有关,但我无法找出确切的原因。
编辑 这是关于模板矩阵的:
Matrix<int> a(2, 2, 0); // creates a 2x2 matrix of all zeros
cout << a.getValue(3, 2) << endl; // prints the value at row 3, col 2, which doesn't actually exists; the output is as shown above
另外,值得注意的是,
int b = a.getValue(3, 2);
给出预期的输出:
Invalid x or y.
通过添加解决了它
exit(-1);
到捕获块:
catch (out_of_range &e) {
cerr << e.what() << endl;
exit(-1);
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- AES加密到解密未正确输出
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- C++格式化输出问题
- 将值从二维数组输出到文本文件
- 集合上的输出迭代器:assign和increment迭代器
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 为什么rk4.do_step不输出C++中的初始条件
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何根据单词在文本中出现的概率输出单词