Catch(…)不会捕获所有异常
catch(...) does not catch all exceptions
我遇到了一个关于异常的问题。
代码如下所示,
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
向量的末尾传递,并确保你没有越界。
相关文章:
- 有没有更好的方法来处理异常? try-catch块真的很丑
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 如果一个对象是在本地创建的,并在C++中作为异常抛出,那么本地对象如何在其范围之外有效,即在 catch 块中?
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- 指定特定异常以使用 catch 停止 GDB
- 无法使用 C++ catch(..) 捕获访问冲突异常
- 具有两个类似catch部分的代码的异常处理行为
- 基类catch不捕获异常,即使它出现在派生类catch之前
- 为什么当我抛出派生类的对象时,基类的 catch 块会捕获异常
- C++ 异常中的 catch(异常)是什么意思?
- 格式化文件异常被 try catch 块忽略
- 从catch块调用异常类中的函数并不是打印从try块传递的值
- 从用catch(..)捕获的异常中获取一些信息
- "try catch(...)"可以在 C++ 中捕获哪些异常?
- MFC TRY CATCH与C++对MFC异常的尝试捕获
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- catch站点中异常的常见用法是什么
- catch语句如何在没有反射的情况下识别异常类型
- 如何在这个try-show-catch代码中对异常进行排序
- llvm异常;Catch处理程序未处理,未调用清理