Reputation: 67
I'm creating a function which iterates through a grid of points and returns the indices of all adjacent points. For the edge of the grid, there are adjacent points which do not exist, so I have created a few try blocks to handle these cases. Here is the code:
try {
all_below[j] = Mesh.matrix[r[i]][c[i] - j];
}
catch (const std::out_of_range& oor) {
below = NAN;
below_k = NAN;
}
But whenever I try to run the program, the catch statement doesn't catch the exception and the program crashes (because Mesh.matrix is out of range). What am I doing wrong?
Edit:
matrix is a 2D vector of int.
Upvotes: 1
Views: 2999
Reputation: 79
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
try
{
cout << vec.at(2) << endl;
}
catch (const out_of_range& e)
{
cerr << e.what() << endl;
}
Upvotes: -1
Reputation: 311126
If all_below and Mesh.matrix are arrays then arrays do not throw any exception if you are using an index outside the available range.
And as noted @Mooing Duck the subscript operator of vectors also does not throw an exception. It is member function at() that throws an exception.
Upvotes: 3
Reputation: 35455
std::vector does not throw exceptions on out-of-bounds access using vector's operator [ ]. If you want an exception to be thrown, then use the vector::at() function instead of [ ].
Upvotes: 0