Alaya
Alaya

Reputation: 3387

Why isn't my exception caught

I am calling a function which comes from a static library, it threw nlopt exception, so I used the following code to locate the exception.

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

But I got the following output message:

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

It seems that the predictor.train(); threw the exception, but why didn't it caught by catch(...)? shouldn't it catch everything?

It looked at the source code of GP::train(), it did throw an nlopt::forced_stop() exception that is not properly caught, but still, I don't understand why the catch(...) didn't catch it successfully.

Upvotes: 1

Views: 155

Answers (1)

eerorika
eerorika

Reputation: 238301

shouldn't it catch everything?

Only if the handler is reached. There are situations where an exception can not be caught and std::terminate is called instead.

[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 ]

Upvotes: 2

Related Questions