c++ - 为什么我的异常没有被捕获

标签 c++ c++11 exception

我正在调用一个来自静态库的函数,它抛出了 nlopt 异常,所以我使用以下代码来定位异常。

    try
    {
        reg_info("Before GP");
        omp_set_num_threads(1);
        GP predictor(train_in, train_out);
        predictor.set_noise_lower_bound(1e-3);
        reg_info("Before Train");
        predictor.train();
        reg_info("After Train");
        reg_info("Before Predict");
        predictor.predict(pred_in, pred_y, pred_s2);
        reg_info("After Predict");
        reg_info("After GP");
    }
    catch(...)
    {
        reg_info("Exception");
    }

但我得到了以下输出消息:

 Info  : Before GP
 Info  : Before Train
terminate called after throwing an instance of 'nlopt::forced_stop'
  what():  nlopt forced stop

好像是predictor.train();抛出了异常,但是为什么没有被catch(...)捕捉到呢?它不应该捕获一切吗?

它查看了 GP::train() 的源代码,它确实抛出了一个未被正确捕获的 nlopt::forced_stop() 异常,但仍然,我不明白为什么 catch(...) 没有成功捕获它。

最佳答案

shouldn't it catch everything?

仅当到达处理程序时。在某些情况下无法捕获异常,而是调用 std::terminate

[except.throw]/7 If the exception handling mechanism, after completing the initialization of the exception object but before the activation of a handler for the exception, calls a function that exits via an exception, std::terminate is called

[except.ctor]/1 As control passes from the point where an exception is thrown to a handler, destructors are invoked by a process, specified in this section, called stack unwinding. If a destructor directly invoked by stack unwind- ing exits with an exception, std::terminate is called (15.5.1). [ Note: Consequently, destructors should generally catch exceptions and not let them propagate out of the destructor. — end note ]

关于c++ - 为什么我的异常没有被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035913/

相关文章:

带有模板化参数的 C++ 函数模板

c++ - 如何使用 PortAudio 和 OpenCV 避免不一致的音频播放?

c++ - Bubblesort 由于某种原因无法正常工作

c++ - 列表初始值设定项

c++11 - std::function 没有名为 'target' 的成员

c++ - 可变参数模板 : producing a tuple of pairs of adjacent elements

java - 如何在 Java 7 中使用方法句柄类调用底层 void 方法?

生产中的 WCF "Too many active security negotiations"错误

java - 如何简化用户输入

c++ - Visual Studio 2015 社区 ZeroMQ 静态库链接错误