Re: try-catch destructor
Hi,
Hi Larry,
In this case, I am afraid that you may need to control the release by
yourself since the CTest instance was created on heap.
Your code may be changed like this:
void CTest_TryCatchDlg::TestMemoryLeak()
{
Ctest *p = NULL;
try
{
p = new CTest();
WillThrowException();
}
catch(...)
{
delete p;
OutputDebugString("Temp");
}
}
I think the OP wanted just a conceptional "how does it work" information. So
I want to add a bit:
In the catch(...) situation you might have caught a system exception like an
access violation so trying to continue the app might be a bad idea as you
cannot know what has gone wrong and what state of the app is broken. So
calling delete p might again throw which terminates the app. If it does
continue it might die some time later, because of whatever damage caused the
exception.
Swallowing exceptions like in the above code is therefor IMHO a bad idea. I
would not do much more then log the error in a catch(...) to save some
debugging information and then call throw; to rethrow the exception. That at
least gives you the chance to trigger a debugger or to get a memory dump for
later analysis. The earlier after the exception the dump is written the
closer you are to the cause of the error. Use that to fix the cause not the
symptom!
So besides using the above code to learn about stack and heap variables,
please learn not to swallow general exceptions which you cannot handle.
Handling and swallowing specific exceptions thrown by design (file not
found, resource not available...) is of course OK.
--
SvenC