// The following code works fine, throwing a std::out_of_range exception:
std::vector<double> vd{ 1.5 };
try {
int i{ -1 };
double d = vd.at(i); // exception is thrown
}
catch (std::out_of_range& re) {
std::cout << "Exception is " << re.what() << std::endl; // invalid vector subscript
}
如果我在for循环中使用无效索引访问向量元素,即使我使用了.at()
,也不会抛出std::exception
异常。为什么没有抛出std::out_of_range
异常?
// in a for loop, this does not throw the exception!
std::vector<double> vd{ 1.5 };
try {
for (int i = -1; i < vd.size(); ++i)
double d = vd.at(i); // exception is not thrown. Why?
}
catch (std::out_of_range& re) {
std::cout << "Exception is " << re.what() << std::endl; // exception is not thrown
}
at
时,同样会发生从有符号到无符号的转换,因为它需要一个无符号参数。 - john