我正在调用一个来自静态库的函数,它抛出了 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/