Question

I am writing a C++ code that controls a special device that is the fusion of several SDKs. My code looks like

#define sdk1SafeCall(err) __sdk1SafeCall(err,__FILE__,__LINE__)

int errorcode = 0;
sdk1SafeCall(sdk1_InitializeDevice());
errorcode=sdk2_InitializeDevice();
errorcode=sdk3_InitializeDevice();

if (some_parameter)
{
    errorcode=sdk2_readDevice(true);
}
else
{
    errorcode=sdk3_writeDevice();
}
label again: errorcode=sdk1_readDevice();
if (error) goto again;

errorcode=close_everything();

Use parameters will rearrange the control flow. My current method uses something like cudaSafeCall to wrap the error codes and exit. What I don't know how to do is where to store detailed explanations of these errors or how to recover from them (such as the goto example). At the end of the day the code looks really messy.

Edit

I do sometimes handle errors with a wrapper.

Was it helpful?

Solution

Writing error-safe code is hard. In your pseudocode, you don't actually deal with errors at all. errorcode will just have the result of "close_everything()" - which may have succeeded, even if everything else went wrong.

The typical way to solve this sort of thing in C++ is to have an object for each "resource" (e.g. a "device"), and throw an exception if something goes wrong that you don't expect to recover from. Wrap the whole function [or an outer set of functions] in a try/catch block.

Of course, if "failure is normal" (e.g. you try to read from a network port, and you get a timeout because there was no data available, that's not something you should throw an exception for). This should use a return-value.

Note that using objects to handle resources requires careful design of the code and especially that your destructor does a good job of cleaning it is run after an exception. Make sure you don't leave things behind if you throw an exception in a constructor - as that is how you get leaks.

There are naturally a whole host of other solutions - after all, we're talking programming, so there's always at least 11 different ways to solve something.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top