473,322 Members | 1,778 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,322 software developers and data experts.

Proper Way to catch exception thrown by new keyword

I'm reading The C++ Programming Language by Bjarne Stroustrup and I
was unclear as to the proper way to catch an exception thrown by the
new keyword. I was wondering if someobody here could let me know if I
have written the following code correctly.

<CODE_SNIP>
#include <iostream>
#include <new>

using std::cerr;
using std::bad_alloc;

int main()
{
char *p;

try
{
for(; ;)
p = new char[100000];
}

catch(bad_alloc)
{
cerr << "Error allocating memory...\n";
return 1;
}

delete p;

return 0;
}

</CODE_SNIP>

I thank you in advance for any pointers you can provide.

Sean
Jul 19 '05 #1
5 4742

"Fao, Sean" <en**********@yahoo.com> wrote in message
news:98**************************@posting.google.c om...
I'm reading The C++ Programming Language by Bjarne Stroustrup and I
was unclear as to the proper way to catch an exception thrown by the
new keyword. I was wondering if someobody here could let me know if I
have written the following code correctly.
Well that depends on what you want it to do.

<CODE_SNIP>
#include <iostream>
#include <new>

using std::cerr;
using std::bad_alloc;

int main()
{
char *p;

try
{
for(; ;)
p = new char[100000];
Are you trying to loop until you run out of memory?

If two allocations succeed then this loop will leak memory. Because the
second allocation will overwrite the first and you will never be able to
free that memory.
}

catch(bad_alloc)
This isn't wrong but usually you catch exceptions using a const reference,
to avoid copying the exception object unnecessarily.

catch (const bad_alloc&)
{
cerr << "Error allocating memory...\n";
return 1;
}

delete p;

return 0;
}

</CODE_SNIP>

I thank you in advance for any pointers you can provide.

Sean


Looks OK.

john
Jul 19 '05 #2
Fao, Sean wrote:
delete p;


In addition to what join said, this line will always be reached, even when
an exception occurs. You may want to add a check (initialise p to NULL and
check for that for instance, or place the delete still inside the try block)
whether you really have any memory to delete.

Also you are allocating with new[], do you should free with delete[]. It
doesn't make any difference here because char is a basic type, but it's good
practice to do it anyway: it adds clarity and gets you in the habit so you
don't forget it when it does make a difference.

--
Unforgiven

"Earth. It exists only in a corner of my memory."
Lord Dornkirk
The Vision of Escaflowne

Jul 19 '05 #3

"Unforgiven" <ja*******@hotmail.com> wrote in message
news:be************@ID-136341.news.dfncis.de...
Fao, Sean wrote:
delete p;
In addition to what join said, this line will always be reached, even when
an exception occurs. You may want to add a check (initialise p to NULL and
check for that for instance, or place the delete still inside the try

block) whether you really have any memory to delete.
Actually there's a return in the catch block, so the delete is not reached
when an exception occurs.

Also you are allocating with new[], do you should free with delete[]. It
doesn't make any difference here because char is a basic type, but it's good practice to do it anyway: it adds clarity and gets you in the habit so you
don't forget it when it does make a difference.


Good point.

john
Jul 19 '05 #4
John Harrison wrote:
"Unforgiven" <ja*******@hotmail.com> wrote in message
news:be************@ID-136341.news.dfncis.de...
Fao, Sean wrote:
delete p;


In addition to what join said, this line will always be reached,
even when an exception occurs. You may want to add a check
(initialise p to NULL and check for that for instance, or place the
delete still inside the try block) whether you really have any
memory to delete.


Actually there's a return in the catch block, so the delete is not
reached when an exception occurs.


Oops, didn't see that ^_^

--
Unforgiven

"Earth. It exists only in a corner of my memory."
Lord Dornkirk
The Vision of Escaflowne
Jul 19 '05 #5
"Fao, Sean" <en**********@yahoo.com> wrote in message
news:98**************************@posting.google.c om...
I'm reading The C++ Programming Language by Bjarne Stroustrup and I
was unclear as to the proper way to catch an exception thrown by the
new keyword. I was wondering if someobody here could let me know if I
have written the following code correctly.


I appreciate your comments, I have rewritten the code using your
recomendations.

Thank you much...

Sean

Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Tilfried Weissenberger | last post by:
Hi, I am a bit confused as to what the FINALLY block is meant for. What's the difference between: this.Cursor = Cursors.WaitCursor; try { //do some stuff } catch { //handle exception }...
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
7
by: Sean Kirkpatrick | last post by:
I got caught with my pants down the other day when trying to explain Try...Catch...Finally and things didn't work as I had assumed. Perhaps someone can explain to me the purpose of Finally. I've...
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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.