How to catch .erase exception in vectors?

送分小仙女□ 提交于 2021-02-17 04:54:30

问题


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.


回答1:


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.




回答2:


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());
}


来源:https://stackoverflow.com/questions/25225281/how-to-catch-erase-exception-in-vectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!