How to end C++ code directly from a constructor? - c++

I would like my C++ code to stop running with proper object cleanup if a certain condition is met; in a constructor of a class.
class A {
public:
int somevar;
void fun() {
// something
}
};
class B {
public:
B() {
int possibility;
// some work
if (possibility == 1) {
// I want to end the program here
kill code;
}
}
};
int main() {
A a;
B b;
return 0;
}
How can I terminate my code at that point doing proper cleanup. It's known that, std::exit does not perform any sort of stack unwinding, and no alive object on the stack will call its respective destructor to perform cleanup. So std::exit is not a good idea.

You should throw an exception, when the constructor fails, like this:
B() {
if(somethingBadHappened)
{
throw myException();
}
}
Be sure to catch exceptions in main() and all thread entry functions.
Read more in Throwing exceptions from constructors. Read about Stack unwinding in How can I handle a destructor that fails.

It is not possible to perform just from a constructor. If you throw an exception then applications need to set up a proper exception handling code at entry points, because if you just thrown an exception that won't be handled then compiler is allowed to skip stack unwinding and cleanup.

If you don't want to use use exceptions, you can have an init method in class B that returns a return code:
class B {
public:
B(/*parameters that will be used by init*/) : ...
int init(); // actually initialize instance and return non 0 upon failure
}

Related

How to end the program from a function which is called in another function (C++)

I have a loop of functions that I called like the code I wrote below and I want at some point to end the program.The problem is that I don't want to use exit function because I have data allocated dynamic also I could use an if in every function and exit one by one but I think will make the code a lot harder to understand and I have more than 3 functions like this.
void c()
{
//code
//I want to exit the program
}
void b()
{
c();
//code
}
void a()
{
b();
//code
}
int main()
{
a();
return 0;
}
Thanks for the help.
You can return from all functions all the way to main (nicest).
You can call some variant of exit.
You can throw an exception.
You can use setjmp/longjmp to jump to the end of main (please don't).
You can crash the application (by calling abort, raise(SIGKILL) or similar).
I can't think of more options, but there may well be some...
Inside your functions used std::unique_ptr wherever you need dynamic allocations.
Then modify :
int main()
{
try
{
a();
}
catch(...)
{ /*... */}
return 0;
}
Then inside any of the deep functions, throw can be used, and std::unique_ptr will release the resources auto-magically.

statically initialized objects can't be placed in the block try

I'm reading the book Inside the C++ Object Model and I got a paragraph as below:
There are a number of drawbacks to using statically initialized
objects. For example, if exception handling is supported, these
objects cannot be placed within try blocks. This can be particularly
unsatisfactory with statically invoked constructors because any throw
will by necessity trigger the default terminate() function within the
exception handling library.
If I get it correctly, it means that
MyGlobalObject obj;
int main()
{
try
{
// do something with obj here is unsatisfactory
}
catch(...){}
return 0;
}
is not good. But I don't know why. Why any throw will be necessity trigger the default terminate() function.
What it means is you can't catch exceptions from statically initialized objects because they are initialized before main() starts making it impossible to surround them with a try{} block.
MyGlobalObject obj; // this initializes before main() starts
int main()
{
try
{
// too late to protect the static initialized global
// with this try block during its initialization
// but any operations you perform on it afterwards
// inside this try{} block will be fine.
}
catch(std::exception const& e)
{
}
}
One solution to this is to put the static objects in a function like this:
MyGlobalObject& get_my_global_object()
{
// This will not initialize until this function
// is called for the first time.
static MyGlobalObject obj;
return obj;
}
int main()
{
try
{
// now if the global object throws during its
// initializatin the exception will be caught.
MyGlobalObject& obj = get_my_global_object();
}
catch(std::exception const& e)
{
}
}

Can I catch an exception thrown before main()?

I have some library (actually the tbb library compiled with a different compiler), throwing an exception before main() proper started. Is there a way to catch that?
int main() { std::cout << "Hello World" << std::endl; }
gives
terminating with unexpected foreign exception
Abort (core dumped)
if I link against said library (which is not used in this example, but in other code it will be).
Generally speaking, it is not possible in standard C++ to catch an exception that is thrown during construction of a global variable (which is outside scope of any function).
I believe the closest possibility is to use a function-try-block for the body of the constructor of the static.
class MyStatics
{
public:
MyStatics();
private:
X x; // construction may fail
Y y; // construction may fail
// etc
};
static MyStatics all_my_statics;
MyStatics::Mystatics() : x(), y() // implement using a function try block
try
{
if (some_condition) throw some_exception(); // construction may even fail here
}
catch (SomeException &)
{
// handler for SomeException
}
If an exception is thrown during construction of all_my_statics, then any fully-constructed members of it will be destructed (i.e. MyStatics members do not exist within such a catch block).
Within the catch block there aren't many options, after reporting about the caught exceptions. The main options will be;
throw (or rethrow) an exception (since the construction of MyStatics has failed). That exception will cause std::terminate() to be called.
terminate the program in some other way deemed to be "cleaner".
It is not a good idea to swallow an exception thrown during construction of a static since the program (e.g. within main()) will have no indication that statics it relies on have not been properly constructed.
It is more usual to place the static object within a function
X &the_x()
try
{
static X thing;
return thing;
}
catch (Whatever &)
{
// handler
}
Bear in mind that every call of the_x() will attempt to construct thing until one of them succeeds (i.e. if an exception is thrown the first time, the second call will attempt to construct thing, etc). However, if the first call of the_x() within the program can be identified and exceptions from it caught (i.e. wrap it in a try/catch) it is not necessary to catch exceptions from subsequent calls - since, if the first call doesn't throw, the construction of thing has succeeded, and it will not be constructed again.
I found this interesting source. It bases his construction on std::terminate functionality
He proposes to use a sort of global try...catch (you can't continue anymore to run, but you can act depending of exception):
[[noreturn]] void onTerminate() noexcept
{
if( auto exc = std::current_exception() ) {
// we have an exception
try{
rethrow_exception( exc ); // throw to recognize the type
}
catch( MyException const& exc ) {
// additional action
}
catch( MyOtherException const& exc ) {
// additional action
}
catch( std::exception const& exc ) {
// additional action
}
catch( ... ) {
// additional action
}
}
std::_Exit( EXIT_FAILURE );
}
and to register this caller when an exception occurred, earliest possible:
const auto installed{ std::set_terminate(&handler) };
int main() {
// run...
}
But you have to know that you can't be sure that std::set_terminate will be called before any instanciation.

Detecting when destructor running due to exception being thrown?

What is a good way in C++ to detect in a destructor that it is being run during unwind of the stack due to an exception being thrown as opposed to a normal exit of scope triggering the destructor? I'd like to know so that I can create a class that has some cleanup code that is always run on normal exit but skipped when an exception occurs.
std::uncaught_exception() (defined in <exception>) will tell you in your destructor if it was called because of an exception:
class A
{
public:
~A()
{
if (std::uncaught_exception()) {
// Called because of an exception
} else {
// No exception
}
}
};
Probably this article will help you. The article will show you the problems with std::uncaught_exception() and contains an advice how to deal with exceptions in destructors.
Don't do that unless you have a good reason. The stack unwinding is such a language feature that all automatic objects inside try block will be enforced to deallocate, so that the resources inside them have a chance to release.
You want skip cleanup in dtor during stack unwinding, which bypasses the original intention of it. And you'll run the risk of leaking resources.
Example
class CDBConnection
{
public:
CDBConnection()
{
m_db.open();
}
~CDBConnection()
{
if (!std::uncaught_exception())
m_db.close();
// if this is called during a stack unwinding,
// your DB connection will not be closed for sure.
// That's a resource leakage.
}
//..
private:
DB m_db;
};
void main()
{
//..
try
{
// code that may throw
CDBConnection db;
//..
}
catch(const CDBException& exp)
{
// properly handle the exception
}
}
Here is one way I can think of, but it seems clumsy:
{
myCleanupClass unwindAction;
try {
// do some work which may throw exception.
} catch (...) {
unwindAction.disableDestructorWork();
throw;
}
}

Way for C++ destructor to skip work when specific exception being thrown?

I have an object on the stack for which I wish its destructor to skip some work when the destructor is being called because the stack is being unwound due to a specific exception being thrown through the scope of the object on the stack.
Now I could add a try catch block inside the scope of the stack item and catch the exception in question and notify the stack object to not run the work to be skipped an then rethrow the exception as follows:
RAII_Class pending;
try {
doSomeWorkThatMayThrowException();
} catch (exceptionToSkipPendingDtor &err) {
pending.notifySkipResourceRelease();
throw;
}
However, I'm hoping there is a more elegant way to do this. For example imagine:
RAII_Class::~RAII_Class {
if (detectExceptionToSkipPendingDtorBeingThrown()) {
return;
}
releaseResource();
}
You can almost do this with std::uncaught_exception(), but not quite.
Herb Sutter explains the "almost" better than I do: http://www.gotw.ca/gotw/047.htm
There are corner cases where std::uncaught_exception() returns true when called from a destructor but the object in question isn't actually being destroyed by the stack unwinding process.
You're probably better off without RAII because it doesn't match your use case. RAII means always clean up; exception or not.
What you want is much simpler: only release resource if an exception is not throw which is a simple sequence of functions.
explicitAllocateResource();
doSomeWorkThatMayThrowException();
explicitReleaseResource(); // skipped if an exception is thrown
// by the previous function.
I would do it the other way around - explicitly tell it to do its work if no exception was thrown:
RAII_Class pending;
doSomeWorkThatMayThrowException();
pending.commit(); // do or prepare actual work
This seems to circumvent the main reason to use RAII. The point of RAII is that if an exception happens in the middle of your code you can still release resources/be destructed properly.
If this isn;t the semantic you want, then don't use RAII.
So instead of:
void myFunction() {
WrapperClass wc(acquireResource());
// code that may throw
}
Just do:
void myFunction() {
Resource r = acquireResource();
// code that may throw
freeResource(r);
}
If the code in the middle throws, the resource won't be freed. This is what you want, rather than keeping RAII (and keeping the name) but not implementing RAII semantics.
Looks like bool std::uncaught_exception(); does the trick if you want to have this behavior for every exception, not just special ones!
You can do without a try-catch:
RAII_Class pending;
doSomeWorkThatMayThrowException(); // intentional: don't release if throw
pending.releaseResource();
Alternatively, you can try a little harder with RAII:
struct RAII_Class {
template<class Op>
void execute(Op op) {
op();
releaseResources();
}
private:
void releaseResources() { /* ... */ }
};
int main(int argc, char* argv[])
{
RAII_Class().execute(doSomeWorkThatMayThrowException);
return 0;
}
Although it would be a kludge at best, if you own the code for the exception class you're interested in, you could add a static data member to that class (bool) that would be set to "true" in the constructor for objects of that class, and false in the destructor (might need to be an int that you increment/decrement instead). Then in the destructor of your RAII class, you can check std::uncaught_exception(), and if true, query the static data member in your exception class. If you get true (or > 0) back, you've got one of those exceptions--otherwise you ignore it.
Not very elegant, but it would probably do the trick (as long as you don't have multiple threads).
I found this website with an interesting discussion about std::uncaught_exception() and an alternative solution to your question that seems much more elegant and correct to me:
http://www.gotw.ca/gotw/047.htm
// Alternative right solution
//
T::Close() {
// ... code that could throw ...
}
T::~T() /* throw() */ {
try {
Close();
} catch( ... ) {
}
}
In this way you're destructor does only one thing and you're protected against throwing an exception during an exception (which I assume is the problem you're trying to solve).