std :: out_of_range异常奇怪的输出

时间:2017-06-22 18:49:39

标签: c++ exception try-catch throw

所以我在模板类中有这个功能:

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

我已经尝试了一个小时来弄清楚这个来自哪里,我错过了什么?它肯定与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.

1 个答案:

答案 0 :(得分:0)

通过添加

解决了这个问题
exit(-1);

到catch区块:

catch (out_of_range &e) {
   cerr << e.what() << endl;
   exit(-1);
}
相关问题