Re: is such exception handling approach good?
George wrote:
:: Hi Ben,
::
::
:: I do not quite agree.
::
::::: oops, it can't either.
:::::
::::: http://www.gotw.ca/gotw/066.htm
::::
:::: which statements do you mean in this article mentioned we can
:::: not use try and catch block in constructor to free resources if
:::: there are any exceptions
:::: in constructor? I can not find. And it is appreciated if you
:::: could point out.
:::
::: A function-try block is different from a try block inside the
::: function.
::
:: suppose we have a class which has a member variable int*, and in
:: constructor we have succeed in allocating memory and assign the
:: int* to the memory block.
::
:: Then in some other code in the constructor, there are exception.
:: Then we can in the exception handler block of constructor. I think
:: in the handler, we should free the memory using delete or
:: delete[], then re-throw the exception. Is it good code? Any
:: potential issues?
::
Not particularly good. :-)
If at all possible, you should try the "dangerous" stuff first, before
allocating any extra memory. That way the exception has no effect.
Or else, you could put the memory allocation inside a member of you
class, and let the member handle the deallocation (RAII :-). Note
that memory is just one of many kinds of resources that your program
could leak! How do you handle the rest?
Bo Persson