Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing/catching exceptions from C'tor of a static object in C++

I have a case in which I have to read an input file in the C'tor, but sometimes this file doesn't exist. This object is usually held statically, so its C'tor is called while loading the dll. I can't catch the exception I throw if the file doesn't exist because it's too early, and my executable crashes in an ugly way. I know it's bad practice to throw exceptions out of a C'tor, but I can't go on if the file doesn't exist, so I have to. Is there a way to catch the exception while loading the dll, and if not, is there any better solution for this scenario?

Thanks, Gal

like image 539
Gal Goldman Avatar asked Dec 06 '22 07:12

Gal Goldman


1 Answers

I assume the static object has the file scope (it is outside any function/class definition). You may consider moving it to an accessor function and accessing it only via that function, like this:

class Object;
Object& getObject()
{
    static Object object;
    return object;
}

The static instance of Object will be initialized upon the first calling of the getObject() method. If the Object's constructor throws, you can easily catch the exception. Just you need to remember wrapping every call of getObject() into a try/catch block (or suffer from the exception bubbling up the stack chain); that may be a bit inconvenient, but on the other hand you may decide to wrap just the logically "first" call, if you know which one it is in the program logic flow.

like image 94
Vlado Klimovský Avatar answered Dec 28 '22 23:12

Vlado Klimovský