473,320 Members | 1,951 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

how to handle exception in constructor

bajajv
152 100+
hi.. if a class A contains an array of objects of another class B.. And in the constructor of A, while constructing objects of B, any one object throws an exception, then how can we guarantee to release all the memory acquired.. so that there is no memory leak..

It was asked in an interview recently.. I was not very sure how to answer this.. can any one help please...

Expand|Select|Wrap|Line Numbers
  1. class B{};
  2. class A{
  3. public:
  4.   B Array[100];
  5.   ...
  6. };
  7.  
In the above code, if in constructor of A, suppose 99 objects of B are constructed successfully, but 100th object throws exception, then how can we guarantee to release all the memory acquired by the other 99 objects?
Apr 14 '12 #1

✓ answered by weaknessforcats

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:

Expand|Select|Wrap|Line Numbers
  1. void MyFunction(A*& ptr)
  2. {
  3.      ptr = 0;  //the pointer to the allocated memory
  4.     try
  5.     {
  6.        ptr = CreateArray();    //maybe a throw here
  7.     }
  8.     catch (...)
  9.     {
  10.        delete [] ptr;  //release allocated memory
  11.        ptr =0;
  12.        throw;          //re-throw original eception
  13.     }
  14.  
  15. }
However your example:
Expand|Select|Wrap|Line Numbers
  1. class A{
  2.  public:
  3.    B Array[100];
  4.    ...
  5.  };
  6.  
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:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    A* ptr = 0;   //the address of our A object
  4.    try
  5.    {
  6.       ptr = new A;
  7.    }
  8.    catch (...)
  9.    {
  10.       delete A;    //creation failed
  11.       ptr = 0;     //set our pointer to A to zero
  12.    }
  13. etc...
  14.  
  15. }
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.

1 1874
weaknessforcats
9,208 Expert Mod 8TB
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:

Expand|Select|Wrap|Line Numbers
  1. void MyFunction(A*& ptr)
  2. {
  3.      ptr = 0;  //the pointer to the allocated memory
  4.     try
  5.     {
  6.        ptr = CreateArray();    //maybe a throw here
  7.     }
  8.     catch (...)
  9.     {
  10.        delete [] ptr;  //release allocated memory
  11.        ptr =0;
  12.        throw;          //re-throw original eception
  13.     }
  14.  
  15. }
However your example:
Expand|Select|Wrap|Line Numbers
  1. class A{
  2.  public:
  3.    B Array[100];
  4.    ...
  5.  };
  6.  
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:

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.    A* ptr = 0;   //the address of our A object
  4.    try
  5.    {
  6.       ptr = new A;
  7.    }
  8.    catch (...)
  9.    {
  10.       delete A;    //creation failed
  11.       ptr = 0;     //set our pointer to A to zero
  12.    }
  13. etc...
  14.  
  15. }
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.
Apr 14 '12 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? ...
5
by: Vitling | last post by:
For no apparent reason, a NullReference exception is thrown in system.dll (System.Net.Sockets.OverlappedAsyncResult.CompletionPortCallback). Since I only get a disassembly from Visual Studio, it...
3
by: Versteijn | last post by:
Hello all, I have a custom Exception inherited class with the following constructor. I added the IIf call because the Parameters() value might be null. But somehow I keep getting an...
3
by: Neelesh Bodas | last post by:
Hello all, Just wanted a small clarification on these two points : 1) The following code compiles well - int f() try { throw "xyz"; } catch(...) {
3
by: elziko | last post by:
I have a procedure that creates a bitmap of a certain size and then displays it in a 3rd party component. However, if the bitmap is very large then a System.OutOfMemoryException is thrown my...
1
by: matt.arens | last post by:
here is some background: I am using the MQSeries/Websphere .Net classes provided by Microsoft. The Websphere Windows Client software is required in order to use the ..Net classes. However, I...
1
by: zeeshansohail | last post by:
Hi, I am facing a problem. As i don't know, how to handle EXCEPTION in ORACLE (PL/SQL). Please if someone can help me to solve out this problem. I will be grateful to him/her. Wating for...
0
by: yogeeswar | last post by:
HI ALL I need to write a SP having a set of deletion queries and any one of query fails then all the previously deleted records need to be rollback. And there is a possibility of deleting a record...
3
by: sudhivns | last post by:
Hi Pals, Application main(), handles the default Exception. However at Method(function) level i want to catch certain exceptions. certain method X(), using all...
9
by: =?Utf-8?B?UmFq?= | last post by:
How do I know which methods will throw exception when I am using FCL or other third party .Net library? I am developer of mostly native Windows applications and now .Net. After working few...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.