[英]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塊:
catch (out_of_range &e) {
cerr << e.what() << endl;
exit(-1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.