Reputation: 51
I have tried to find this question elsewhere, but the problem I'm having still doesn't make sense to me. I'm using Visual C++ 2010 and my program is having out of range errors with vectors. The problem is, it never tells me which vector and the code is prohibitively large to check each one. I wanted to cut things down with try-catch, but I can't get them to catch. Here is some example code I made to demonstrate.
try{
std::vector<int> test;
for(int i=0; i<10; i++){
test.push_back(5);
}
if(test[10]=5)
{
}
if(test[-1]=5)
{
}
}
catch(std::exception ex)//also tried exception& and exception*
{
std::cout << "blah";
}
catch(...){
std::cout << "blah";
}
From other posts, I found suggestions about passing by reference, using ..., and a claim that vector exceptions were always caught by std::exception.
So is there anything else that would keep this from catching?
Upvotes: 2
Views: 2732
Reputation:
std::vector::operator[]
does not check array bounds, and therefore does not throw C++ exceptions. So in your case you program's behavior is undefined (aka UB).
You have to use std::vector::at
to access elements with bounds checking, which throws std::out_of_range
if !(pos < size())
.
On a side note, always catch exceptions by constant reference, like so:
try {
// ...
} catch(const exception_type_here& e) {
// ...
}
And never use catch-all clause without re-throw (like in your second catch
). Never.
Hope it helps. Good Luck!
Upvotes: 3
Reputation: 171177
Refer to the docs - std::vector::operator[]
does not do range checking and does not throw exceptions - if you pass an out-of-bounds index, it simply invokes Undefined Behaviour. If you want an exception to be thrown, use std::vector::at()
instead.
And the preferred way of catching a typed exception is by reference: catch (std::exception &ex)
.
Upvotes: 1