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.