Constructors And Exceptions

  • Thread starter Brian Folke Seaberg
  • Start date
B

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.

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
 
K

Kurt Krueckeberg

Brian Folke Seaberg said:
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
};
 
A

Alf P. Steinbach

* 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.
 
M

Mike Wahler

Brian Folke Seaberg said:
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
 
A

Andrew Koenig

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.
 
A

Alf P. Steinbach

* 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.
 
J

Jonathan Mcdougall

Brian said:
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
 
S

Siemel Naran

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[].
 
S

Siemel Naran

Brian Folke Seaberg said:
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.
 
B

Brian Folke Seaberg

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
 
D

Dave O'Hearn

Brian said:
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-lite/how-to-post.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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top