May I call std::terminate directly?

Viewed 297

I have a non-void function which returns a value to be used as an input of a class constructor, but there is a possibility for that value not to be available, so I want to return the value in case of success or just terminate (std::terminate()) the application in case of failure before the function return.

Since std::terminate is called by the runtime according to https://en.cppreference.com/w/cpp/error/terminate, am I obliged to throw an exception and let the runtime decide whether the program is terminated or not?

What about the following warning I read in a simple test I just performed? "terminate called without an active exception"

Am I going in a stupid way?

Thanks for your insights in advance!

2 Answers

... I obliged to throw an exception and let the runtime decide whether the program is terminated or not?

It is up to you. If you want to be able for an exception to be caught somewhere up the call stack then you should throw an exception. In cases you want to terminate because there is no way to recover then calling std::terminate is fine. Just consider that if you throw an exception which is not caught then the program terminates anyhow, so you can choose to either catch it or not, while std::terminate terminates always.

The same page that you linked to, in your question, also has the following statement:

std::terminate() may also be called directly from the program.

Related