This is more of a design suggestion I need. Below code is from a C++ dll that am working on and this dll is called by many client executables. InputParams is a pointer to client exe.
The dll calls functions in the client to get certain values and the client doesn't have any exception build into it. So i need to implement exception handling in dll code.
for e.g., in the line input->getName, if it returns a NULL pointer or if status == ERROR, then I need to throw exception and catch it in GetNumbers function.
void Metrics::GetNumbers(InputParams* input, OutputParams* output)
{
int i, x, k;
int status = 0;
char* mesg;
try{
const char* name = input->getName(&status, &mesg); //this returns a name string
//and status will contain whether success or failure and mesg will have any error
//messages.
const char* age = input->getAge(&status, &mesg);
//Many other similar calls to client
vector <int> myVectorNumers* = input->getNumberArray(&status, &mesg);
vector <int> myVectorInfos* = input->getInfoArray(&status, &mesg);
//Many other similar calls to client;
}
catch (std::exception e&)
{
// TODO
}
catch (string msg)
{
// TODO
}
I came up with a way of doing it. And this is the snippet of code.
string errorMsg = "";
const char* name = input->getName(&status, &mesg);
if (name == NULL || status == ERROR) // ERROR == 0
{
errorMsg = mesg;
throw errorMsg;
}
const char* age = input->getAge(&status, &mesg);
if (age== NULL || status == ERROR)
{
errorMsg = mesg;
throw errorMsg;
}
//Same for other calls to client using **input** pointer
Now as you see, I have to duplicate almost the same code in every place were there should be an exception check.
What am looking for is?
string errorMsg = "";
const char* name = input->getName(&status, &mesg);
CheckException(name, status, mesg, &errorMsg); // this function should do the error check and then throw the exception. And that exception should be caught by catch block in **GetNumbers** function.
const char* age = input->getAge(&status, &mesg);
CheckException(age, status, mesg, &errorMsg);
I have no idea whether even this is possible.
So a dummy implementation of CheckException will look like......
std::exception CheckException (/*1st parameter needs to be template type*/T* var, int status, string mesg, string *errorMsg)
{
if (var == NULL || status == ERROR)
{
errorMsg = mesg;
return /*TODO*/; //Not sure how to return a throw
}
}
1st of all, is this possible? Or is there a better way of doing this?
If you can provide me some sample code, that will be great!
Aucun commentaire:
Enregistrer un commentaire