std::out_of_range异常奇怪的输出

std::out_of_range exception weird output

本文关键字:输出 range out of std 异常      更新时间:2023-10-16

所以我在模板类中有这个函数:

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);
}