Cleaning up after an exception
Suppose my function needs to re-throw an exception - but it needs to clean up before doing so. The obvious solution is somehting like this....
Code:
HRESULT MyFunc()
{
// Declare lots of pointers
char* p1 = NULL;
char* p2 = NULL;
char* p3 = NULL;
char* p4 = NULL;
try
{
// Whatever...
}
catch ( MyException )
{
// Clean up after caught exception
if (NULL != p1)
delete [] p1;
if (NULL != p2)
delete [] p2;
if (NULL != p3)
delete [] p3;
if (NULL != p4)
delete [] p4;
// Re-throw the exception
throw;
}
// Clean up after normal execution
if (NULL != p1)
delete [] p1;
if (NULL != p2)
delete [] p2;
if (NULL != p3)
delete [] p3;
if (NULL != p4)
delete [] p4;
// and return normally
return ERROR_SUCCESS;
}
However, the above strategy requires 2 lots of cleanup code (something I'm always loathe to do because I've found it to be a common cause of programming errors).
Is there a better strategy? - i.e. one that requires only 1 block of cleanup code, regardless of whether an exception occured or not?
"A problem well stated is a problem half solved.” - Charles F. Kettering