Catching out_of_range on a vector of vectors

David Chan picture David Chan · Oct 7, 2013 · Viewed 23.5k times · Source

I have a vector of vectors to establish a map of integers, and I would love to catch a vector out of range error whenever it is thrown, by doing the following:

vector< vector<int> > agrid(sizeX, vector<int>(sizeY));

try {
    agrid[-1][-1] = 5;     //throws an out-of-range
}
catch (const std::out_of_range& e) {
    cout << "Out of Range error.";
}

However, my code doesn't seem to be catching the error at all. It still seems to want to run std::terminate. Does anyone know whats up with this?

Answer

LihO picture LihO · Oct 7, 2013

In case you want it to throw an exception, use std::vector::at1 instead of operator[]:

try {
    agrid.at(-1).at(-1) = 5;
}
catch (const std::out_of_range& e) {
    cout << "Out of Range error.";
}

1 - Returns a reference to the element at specified location pos, with bounds checking. If pos is not within the range of the container, an exception of type std::out_of_range is thrown