473,549 Members | 2,543 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...may be.

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 1761

"Brian Folke Seaberg" <bs*********@ao l.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*********@ao l.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...may be.

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*********@ao l.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...may be.
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.co m> wrote in message
news:G8adnWKVLp 2jP13cRVn-
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*********@ao l.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
counterintuitiv e 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

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

Similar topics

42
5723
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 kind. It sounds simple but evidently .NET has difficulty with this concept for some reason. I do understand that .NET objects are created on the GC...
3
1759
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. Is the reason technical (compiler or CLR limitation) or logical (OOP best practices)? Any feedback would be greatly appreciated.
1
2374
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 std::vector<int> on the stack, using my current STL implementation, as far as I can see, there is no chance for an exception to occur, because the default...
3
2216
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 hard coding them into the class itself. The question I'm pondering is where would be the best place to load these string resources? The string...
1
1265
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) Public Sub New(ByVal message As String, ByVal inner As Exception) It seems that all of the texts say to do this but my custom exception will have it's...
5
1879
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
2807
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 created. And there can never exist a situation where we want to return a value at the time of creation of an object. I don't understand why author...
1
852
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 get executed when threads are created? Thanks! Paul
14
1589
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 exception error, but this means that I have to throw this error back from MyClass constructor, how can I avoid this? Thanks folks!
0
7730
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7971
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6055
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5381
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5101
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1956
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 we have to send another system
1
1068
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
776
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.