By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,156 Members | 1,004 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,156 IT Pros & Developers. It's quick & easy.

Constructors And Exceptions

P: n/a
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
Share this Question
Share on Google+
10 Replies


P: n/a

"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

P: n/a
* 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

P: n/a

"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

P: n/a
"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

P: n/a
* 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

P: n/a
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

P: n/a
"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

P: n/a
"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

P: n/a
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

P: n/a
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 discussion thread is closed

Replies have been disabled for this discussion.