If you have an exception inside any function, then that function terminates. That means any memory you allocated in that function will not get released.
So what you do is catch any exceptions while still inside the function and then release any memory in the catch block. Thereafter, you re-throw the exception:
- void MyFunction(A*& ptr)
-
{
-
ptr = 0; //the pointer to the allocated memory
-
try
-
{
-
ptr = CreateArray(); //maybe a throw here
-
}
-
catch (...)
-
{
-
delete [] ptr; //release allocated memory
-
ptr =0;
-
throw; //re-throw original eception
-
}
-
-
}
However your example:
- class A{
-
public:
-
B Array[100];
-
...
-
};
-
does not apply. It would be the responsibility of B's ctor to do any exception handling. Class A has no responsibility for B. Class A has a stack array of B so it is the compiler who will manage the memory for that array.
Remember in your example: 1) complier allocates a class A object and that includes the 100 element array of B, 2) the compiler calls the default ctor of B for each array element (this is where the exception might occur, and then 3) compiler calls ctor for class A. Nowhere in here do you have any responsibility for memory management.
But let's assume you know the coders for B are a shoddy bunch and you need to protect yourself. In this case you create your A object on the heap and if it doesn't create properly, you delete it:
- int main()
-
{
-
A* ptr = 0; //the address of our A object
-
try
-
{
-
ptr = new A;
-
}
-
catch (...)
-
{
-
delete A; //creation failed
-
ptr = 0; //set our pointer to A to zero
-
}
-
etc...
-
-
}
At the etc... you are still running. If ptr is zero, then you have trouble but you can re-try to create the A object or advise your user that you have to terminate or perhaps advise that the portions of the program requiring ptr have been rendered inactive.