473,508 Members | 2,195 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Constructors And Exceptions

I was recently browsing a couple of C++ books at the local bookstore.

One book called throwing exceptions from constructors a "dubious practice."

Another book recommended not throwing exceptions from constructors due to the
fact that the destructor for the object being constructed will not be executed
and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is dependent
upon the execution of the destructor. The author suggests setting a status
indicator and requiring clients of the class and even member functions of the
class to examine that status indicator prior to accessing members rather than
signaling constructor failure via the exception mechanism.

My initial reaction to the first book was that the practice is not dubious but
is in fact a technique that is accepted by the C++ community at large
(including the originator of the language.)

My initial reaction to the second book was that if programmers understand the
mechanics of object construction and destruction and knew of exception safe
programming techniques such as those taught by Meyers, Sutter and others that
it becomes a perfectly safe method for handling constructor failure.

Dangerous in the hands of the unknowing...maybe.

Dubious...I don't know about that.

Are these authors in the minority?

If one of these guys interviewed me I would not be sure I wanted to work for
them. Of course since these guys are being paid to author C++ books and I am
not I will assume they are the more knowledgeable C++ programmers :)

I am sure all techniques for handling failure have appropriate and
inappropriate contexts in which they can be applied.

I am curious to know what the members of this newsgroup think.

===============
Brian Folke Seaberg
===============

"A noble spirit embiggens the smallest man" -- Jebediah Springfield
Jul 22 '05 #1
10 1755

"Brian Folke Seaberg" <bs*********@aol.com> wrote in message
news:20***************************@mb-m24.aol.com...
I was recently browsing a couple of C++ books at the local bookstore.

One book called throwing exceptions from constructors a "dubious
practice."
Another book recommended not throwing exceptions from constructors due to
the
fact that the destructor for the object being constructed will not be
executed
and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is
dependent
upon the execution of the destructor.


That is why raw pointers should be avoided. Using a managed pointer will
mitigate this problem.

class Sample {
public:
Sample()
{
s_ = new char[5];
throw;
}
private:
auto_ptr<char *> s_; // destructor will free memory if exception
is thrown
};
Jul 22 '05 #2
* Brian Folke Seaberg:
I was recently browsing a couple of C++ books at the local bookstore.

One book called throwing exceptions from constructors a "dubious practice."

Another book recommended not throwing exceptions from constructors due to the
fact that the destructor for the object being constructed will not be executed
and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is dependent
upon the execution of the destructor.

The author suggests setting a status
indicator and requiring clients of the class and even member functions of the
class to examine that status indicator prior to accessing members rather than
signaling constructor failure via the exception mechanism.


Which books were those?

Just so that people reading this thread can steer away from such trash.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #3

"Brian Folke Seaberg" <bs*********@aol.com> wrote in message
news:20***************************@mb-m24.aol.com...
I was recently browsing a couple of C++ books at the local bookstore.
Could you cite the titles and authors please?
One book called throwing exceptions from constructors a "dubious practice."
Another book recommended not throwing exceptions from constructors due to the fact that the destructor for the object being constructed will not be executed and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is dependent upon the execution of the destructor. The author suggests setting a status indicator and requiring clients of the class and even member functions of the class to examine that status indicator prior to accessing members rather than signaling constructor failure via the exception mechanism.

My initial reaction to the first book was that the practice is not dubious but is in fact a technique that is accepted by the C++ community at large
(including the originator of the language.)
I agree.
My initial reaction to the second book was that if programmers understand the mechanics of object construction and destruction and knew of exception safe programming techniques such as those taught by Meyers, Sutter and others that it becomes a perfectly safe method for handling constructor failure.
I agree with this.
Dangerous in the hands of the unknowing...maybe.

Dubious...I don't know about that.
Dubious in the hands of the ignorant, yes.
Are these authors in the minority?
Not necessarily. Unfortunately, there seem to be more C++
books that teach 'dubious' practice as well give simply
wrong info, than there are 'good' ones. The book reviews
at www.accu.org are a good way to filter many of the 'good'
from the 'bad'.

If one of these guys interviewed me I would not be sure I wanted to work for them. Of course since these guys are being paid to author C++ books and I am not I will assume they are the more knowledgeable C++ programmers :)
Not necessarily. See above.

I am sure all techniques for handling failure have appropriate and
inappropriate contexts in which they can be applied.
Yes, virtually everthing depends upon context.

I am curious to know what the members of this newsgroup think.


Now you know what *I* think. :-)

-Mike

Jul 22 '05 #4
"Brian Folke Seaberg" <bs*********@aol.com> wrote in message
news:20***************************@mb-m24.aol.com...
I was recently browsing a couple of C++ books at the local bookstore. One book called throwing exceptions from constructors a "dubious
practice."
Now you know one book to avoid.
Another book recommended not throwing exceptions from constructors due to
the
fact that the destructor for the object being constructed will not be
executed
and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is
dependent
upon the execution of the destructor. The author suggests setting a
status
indicator and requiring clients of the class and even member functions of
the
class to examine that status indicator prior to accessing members rather
than
signaling constructor failure via the exception mechanism.
If a constructor throws an exception, is it responsible for undoing whatever
it did before throwing the exception. I don't see why that should be
surprising.
My initial reaction to the first book was that the practice is not dubious
but
is in fact a technique that is accepted by the C++ community at large
(including the originator of the language.)
Yes.

I should point out that throwing exceptions in DEstructors is a disaster.
My initial reaction to the second book was that if programmers understand
the
mechanics of object construction and destruction and knew of exception
safe
programming techniques such as those taught by Meyers, Sutter and others
that
it becomes a perfectly safe method for handling constructor failure.
Yup.
Dangerous in the hands of the unknowing...maybe.
Everything is dangerous in the hands of the unknowing--at least potentially.
Dubious...I don't know about that.
I'm always willing to listen to arguments, but until I hear one, I don't see
why the notion could be considered dubious.
Are these authors in the minority?
I suspect that a lot of authors don't discuss exceptions at all. They're
hard to teach, especially in parallel with other concepts. I am still not
sure of the best way to integrate exceptions into a C++ curriculum.
If one of these guys interviewed me I would not be sure I wanted to work
for
them. Of course since these guys are being paid to author C++ books and I
am
not I will assume they are the more knowledgeable C++ programmers :)
It depends on the book. Some amazing trash gets published. And no, I won't
name names; it wouldn't be cricket.
I am sure all techniques for handling failure have appropriate and
inappropriate contexts in which they can be applied.


Indeed. Well, maybe "all" is a little strong, because there are surely some
techniques that just plain don't work. Throwing exceptions from
constructors, however, isn't one of them.
Jul 22 '05 #5
* Andrew Koenig:
I am still not sure of the best way to integrate exceptions into a
C++ curriculum.


Perhaps starting right at the "Hello, world!" stage?

<url: http://home.no.net/dubjai/win32cpptut/w32cpptut_01_02.doc> (Word)
section 8 "[Pitfall: Errors that are ignored".

Hopefully that document will be integrated in the HTML-based version
<url: http://home.no.net/dubjai/win32cpptut/html/> soon.

Yes, it's a raw hack, a pedagogical and practical compromize in several
ways.

And I wonder about the language lawyer legality of it, since I'm touting
_correctness_ for that tutorial -- that's the whole point of it.

Any help whatsoever appreciated.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 22 '05 #6
Brian Folke Seaberg wrote:
I was recently browsing a couple of C++ books at the local bookstore.

One book called throwing exceptions from constructors a "dubious practice."


troll alert. if it ain't, take that to comp.std.c++.
Jonathan
Jul 22 '05 #7
"Kurt Krueckeberg" <ku***@pobox.com> wrote in message
news:G8adnWKVLp2jP13cRVn-
class Sample {
public:
Sample()
{
s_ = new char[5];
throw;
}
private:
auto_ptr<char *> s_; // destructor will free memory if exception is thrown
};


The type of s_ is like char**, so your could should not compile. Anyway,
even if you use auto_ptr<char>, the code will compile but it is not correct,
because one must use delete[] to delete arrays. I think the appropriate
container here is std::vector, though I think boost has an auto_ptr like
object that invokes delete[].
Jul 22 '05 #8
"Brian Folke Seaberg" <bs*********@aol.com> wrote in message
One book called throwing exceptions from constructors a "dubious practice."

I disagree. Throwing exceptions from the constructor means that the
constructor tries to initialize the object, which garauntees all objects are
initialized prioir to first use. This makes objects easier to use,
especially as members of a class.

See the response by Kurt for how to avoid memory leaks and such (basically
use classes whose destructors do cleanup, such as auto_ptr, vector,
ofstream).

But there's another thing. What if you're writing the vector class or some
other and you have to make the constructor exception safe? In that case,
you could have a private cleanup function called by the destructor as well
as the constructor's catch block. For example,

class Vector {
public:
Vector(size_t size);
Vector(const Vector&);
Vector& operator=(const Vector&);
~Vector();
private:
int * d_array;
void cleanup() throw();
};

void Vector::cleanup() throw() {
delete[] d_array;
}

Vector::~Vector() { cleanup(); }

Vector::Vector(size_t size) : d_array(NULL) {
try { d_array = new int[size]; }
catch (...) { cleanup(); throw; }
}

You can also put try-catch blocks around the constructor. I think the
syntax is something like this,

try {
Vector::Vector(size_t size) : d_array(new int[size]) {
}
catch (...) { cleanup(); throw; }
Another book recommended not throwing exceptions from constructors due to the fact that the destructor for the object being constructed will not be executed and that as a result any resources allocated by the constructor prior to
throwing the exception will not be deallocated if the deallocation is dependent upon the execution of the destructor. The author suggests setting a status indicator and requiring clients of the class and even member functions of the class to examine that status indicator prior to accessing members rather than signaling constructor failure via the exception mechanism.


Is is easier to remember to have a single cleanup function which you call
from all constructors, the destructor, and maybe operator=? Or easier to
have an infinite number of clients remember to check the flag?

The strength of exceptions is that have to deal with the errors, so in the
long run should make code more fault tolerant. One downside of exceptions
is that they have overhead to runtime code, so they're not recommended for
low level code, like the details of number crunching algorithms.

Jul 22 '05 #9
Jonathan Mcdougall wrote

troll alert. if it ain't, take that to comp.std.c++.


Are you calling me a troll?

If you are I suggest to you that it is completely unwarranted.

I brought up the topic because the book I read made a statement that was
counterintuitive with respect to all that I had been taught regarding
constructors and exceptions. Rather than dismiss the author outright I chose
to try to find out what others in the C++ community felt about his statement.

No trolling involved.

Since I am not trolling then maybe I will consider your advice regarding taking
it to comp.std.c++. I would like to know why that is the more appropriate
forum though.

===============
Brian Folke Seaberg
===============

"A noble spirit embiggens the smallest man" -- Jebediah Springfield
Jul 22 '05 #10
Brian Folke Seaberg wrote:
Since I am not trolling then maybe I will consider your advice
regarding taking it to comp.std.c++. I would like to know why
that is the more appropriate forum though.


The poster was incorrect. Your post would be off-topic in comp.std.c++.
The FAQ is confused about whether it's on-topic here,

http://www.parashift.com/c++-faq-lit...t.html#faq-5.9

It says "code design" is on-topic. Then it says that things are only on
topic here if they could technically be answered by reading the
Standards document, which is a contradiction. It is poor wording. Since
the FAQ is full of Q&A's of the form "Is this bad to do in C++, and
what do I do instead?" it's obvious that stuff is on topic.
--
Dave O'Hearn

Jul 22 '05 #11

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

Similar topics

42
5721
by: Edward Diener | last post by:
Coming from the C++ world I can not understand the reason why copy constructors are not used in the .NET framework. A copy constructor creates an object from a copy of another object of the same...
3
1751
by: SLE | last post by:
Hi there, I know constructors are not inherited from the base class, not in VB.NET nor C# (nor Java I suppose). I never wondered,but reflecting on the reason why, I cannot find a solid answer. ...
1
2371
by: Shane Groff | last post by:
I'm sorry if this is a FAQ, but I've been unable to find exactly what I'm looking for. Does the STL make the no-throw guarantee for any of the STL containers? E.g. If I have a...
3
2215
by: Wavemaker | last post by:
I'm writing a class whose methods can throw exceptions under certain circumstances. These exceptions will need string messages. I was thinking about placing these messages in a resource instead of...
1
1259
by: Daniel Klein | last post by:
When creating a custom exception that derives from ApplicationException, why is it necessary to have the 3 basic contructors, i.e. Public Sub New() Public Sub New(ByVal message As String)...
5
1874
by: tryptik | last post by:
All- I have heard differing points of view on whether or not constructors should throw. I am working on a library, and I need to know if it is bad form for a consturctor to throw. Thanks -J
6
2801
by: Kavya | last post by:
I was reading a book Test Your C++ Skills by Yashwant Kanetkar. There was a question in it Ques: Why constructors do not have return values? Ans :Constructors are called whenever an object is...
1
850
by: timexsinclair2068 | last post by:
Hi, I'm getting some exceptions when creating new threads. That might -or might not- have to do with a probable (?) re-execution of shared constructors. Is that possible? Do shared constructors...
14
1582
by: jalqadir | last post by:
The constructor in MyClass instantiates many objects pointers through 'new', I would like to implement a way to make sure that the object has been allocated in memory by catch(ing) the bad_alloc...
0
7227
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7127
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7054
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5633
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5056
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4713
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1564
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
768
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
424
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.