Home > Blockchain >  Try Catch and Static Variables
Try Catch and Static Variables

Time:05-12

Suppose I am doing something like:

try
{
   do_job();
}
catch(...)
{
   std::cout << "GUI is running so we won't terminate and raise a clear error here instead" << std::endl;
};

When calling a failing do_job some static variables/classes are initiated, are they "destroyed" after the catch? If not how to handle this please (i.e. memory allocated to statics)?

My generic problem is: I am having a GUI looping to display stuff to the user, say a game, if an error occur, the program will call std::termniate() I guess, or something similar, but I will find myself in the lovely file <abort>, the GUI then is crached, how can I handle this and reset static variables created when do_job is called please? Shoud I just let them initiated? The user in this case might change mind and not even use the static variables that have been created, so they are there with no use taking memory?

CodePudding user response:

Static storage duration variables, if they have been successfully initialized, will always be destroyed at normal program termination, not earlier.

If a static variable wasn't successfully initialized then it will not be destroyed.

In any case there is nothing for you to take care of under normal conditions. In particular when throwing from do_job, either the static has been fully initialized at the point of the throw or it hasn't been. In the former case it will be destroyed at normal program termination, in the latter case it doesn't need to be destroyed.

In the situation of a std::terminate call, it looks different. It is called under abnormal conditions, such as if an exception is uncaught or an exception thrown while stack unwinding is in progress or an exception escapes a noexcept function.

The default std::terminate handler will call std::abort which abnormally terminates the program and explicitly does not destruct any static storage duration objects. The program just abruptly terminates without any chance to execute any further instructions (except maybe for a SIGABRT handler).

The std::terminate handler can be replaced, but the conditions under which std::terminate is called don't really allow for normal program termination and surely not for sensible continuation of program execution.

The best solution is to not let the abnormal conditions causing it to be called happen. Make sure to not let exceptions escape from main, destructors or noexcept functions. (There are more sources of std::terminate calls. All of them should be avoided.)

CodePudding user response:

When calling a failing do_job some static variables/classes are initiated, are they "destroyed" after the catch?

Variables with static storage duration are destroyed after main returns (either normally, or call to std::exit).

  • Related