PsP
PsP

Reputation: 696

How to catch .erase exception in vectors?

I have declared this vector in a code and I want to capture .erase exception in the following situation :

When MyVec has no member and I want to delete one of its indices, it will throw an error. I want to capture this error.

if there's no way to capture this kind of error, Does changing std::vector into alternative ones in Qt like Qlist or ... help to find a solution? what about other alternatives in C++ ?

void Main()
{
      std::vector <int> MyVec;
      MyVec.clear();

try    
{

    MyVec.erase(MyVec.begin());
}
catch(...)
{
   qDebug("Hoora I've catched the exception !");
}

}

by the way, I'm working in Linux Ubuntu 12.04 and my IDE is Qt 4.8.

Upvotes: 1

Views: 3253

Answers (2)

user2836797
user2836797

Reputation:

According to the docs,

If the removed elements include the last element in the container, no exceptions are thrown (no-throw guarantee). Otherwise, the container is guaranteed to end in a valid state (basic guarantee). An invalid position or range causes undefined behavior.

Thus std::vector::erase does not necessarily throw an exception if it has no elements. Instead you should check the vector size before erasing.

if (!vector.empty()) 
{
  // Erase the entire vector.
  vector.erase(vector.begin(), vector.end());
}

Upvotes: 3

Brian Bi
Brian Bi

Reputation: 119382

std::vector does not throw an exception when you try to erase an invalid or past-the-end iterator. Instead you just get undefined behaviour.

If you must throw an exception, you can do this:

if (MyVec.empty()) {
    throw std::range_error("MyVec is empty");
    // or maybe std::logic_error or std::runtime_error
}
MyVec.erase(MyVec.begin());

Remember that exceptions are most useful for non-local handling of exceptional conditions, and try to avoid them if you don't need them. That is, if you can do

if (MyVec.empty()) {
    // handle this
} else {
    MyVec.erase(MyVec.begin());
}

then it would be much preferable to throwing an exception.

Upvotes: 3

Related Questions