I can’t seem to get my head around why people say C++ exceptions are better. For example, I have an application which loads function objects from shared objects to be used in the application. What goes on is something like this:
bool LoadFunctions()
{
//Get Function factory.
FunctionFactory& oFactory = GetFunctionFactory();
//Create functions from the factory and use.
}
FunctionFactory& GetFunctionFactory()
{
//Get shared object handle.
void* pHandle = dlopen("someso.so");
//Get function ptr for Factory getter.
typedef FunctionFactory* (*tpfFacGet)();
tpfFacGet pF = static_cast<tpfFacGet>(dlsym(pHandle, "GetFactory"));
//Call function and return object.
return *((*pF)());
}
Now, it’s easy to see that loads of stuff can go wrong. If I did it like I always do, I’d return pointers instead of references, and I’d check if they were NULL and print an error message and get out if they weren’t. That way, I know where things went wrong and I can even try to recover from that (i.e. If I successfully load the factory and fail to load just a single function, I may still continue). What I don’t understand is how to use exceptions in such a scenario and how to recover the program rather than printing an error message and qutting. Can someone tell me how I am to do this in C++ish way?
We don’t even need return codes. If a problem occurs it should be in the exception.
EDIT:
Okay, so lets say that you have an alternative method of loading functions should
LoadFunctions()fail. You might be tempted to call that in thecatchhandler, but this way you’ll quickly end up with a huge amount of nested exception handlers which just complicates things.So now we get down to the question of design.
LoadFunctionsshould succeed if functions are loaded and throw out an exception if it does not. In this hypothetical example of an alternative method of loading functions, that call should be within theLoadFunctionsmethod. This alternative method does not need to be visible to the caller.At the top level we either end up with functions, or we do not. Writing good exception handling, in my opinion is about getting rid of grey areas. The function did what it was told to do, or it didn’t.