Catch(…)不会捕获所有异常

catch(...) does not catch all exceptions

本文关键字:异常 Catch      更新时间:2023-10-16

我遇到了一个关于异常的问题。

代码如下所示,

try
{
    auto it = set_difference(allInterfaces.begin(), allInterfaces.end(), eths.begin(),   
    eths.end(), newCards.begin());
}  
catch(...)
{
  cout << "exception thrown << endl;
}

我知道set_difference()抛出了一个异常,但是程序退出并且catch块没有捕获异常。是否有方法捕获异常?

谢谢你的帮助

set_difference将把两个输入集合中唯一的元素写入您传入的输出范围。确保这个范围足够大以包含结果是您的责任。否则,您将超出范围的界限,导致未定义的行为。当发生这种情况时,不会抛出异常,您可以期望的最佳指示符是在未优化的构建中出现断言失败(并且也不能保证)。

假设newCards是一个支持push_back的容器,最简单的防止方法是使用std::back_insert_iterator,每次将对象赋值给它时,它都会调用push_back

auto it = set_difference(allInterfaces.begin(), allInterfaces.end(), 
                         eths.begin(), eths.end(), std::back_inserter(newCards));

其他选项为std::front_insert_iterator(呼叫push_front())和std::insert_iterator(呼叫insert())。选择一个最适合你需要的

在您的注释的帮助下,您很可能会增加并迭代从newCards.begin()返回的迭代器,甚至超出向量的界限。这会导致未定义行为(在您的情况下会导致崩溃),而不是抛出c++异常。在c++中,迭代器访问没有边界检查(很少有)。

要解决这个问题,你需要在newCards向量的末尾传递,并确保你没有越界。