473,586 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exceptions in constructors

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

Sep 20 '06 #1
5 1880
tr*****@gmail.c om wrote:
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.
Throwing from a constructor is fine. The alternative is to have the
constructor leave the object in an inconsistent state, which is rarely the
better way to go about the problem.
Best

Kai-Uwe Bux
Sep 20 '06 #2
tr*****@gmail.c om wrote:
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.
Destructors should never throw. Constructors should throw if they cannot
put the object into a valid state.

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Sep 20 '06 #3
Daniel T. wrote:
tr*****@gmail.c om wrote:
>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.

Destructors should never throw. Constructors should throw if they cannot
put the object into a valid state.
And all objects should be ready for unit tests. Unit tests often require
objects in a minimally constructed state, without all their baggage. So a
constructor should not sub-construct everything it could possibly use,
because a unit test will just throw it all away.

This isn't just an optimization issue - lean constructors are a sign of
clean designs, and of "constructi on encapsulation".

So the best constructors, following this guideline, are those that do the
minimum to prevent their next expected method, or their constructor, to not
crash. Set your pointers to NULL and return. No hard logic, so no
exceptions.

This guideline has plenty of harmless contradictions; they represent
applying more theory to this basic theory.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Sep 20 '06 #4
Kai-Uwe Bux wrote:
tr*****@gmail.c om wrote:
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.

Throwing from a constructor is fine. The alternative is to have the
constructor leave the object in an inconsistent state, which is rarely the
better way to go about the problem.
Right, as usual. To back you up, here's a quote from _C++ Coding
Standards_ by Sutter and Alexandrescu, Item 72:

"Exception handling is better than the alternatives for reporting
errors from constructors and operators: The copy constructors and the
operators have predefined signatures that leave no room for return
codes. In particular, constructors have no return type at all (not even
void), and and for example every operator+ must take exactly two
parameters and return one object (of a prescribed type; see Item 26).
For operators, using error codes is at least possible if not desirable;
it would require errno-like approaches, or inferior solutions like
packaging status with an object. For constructors, using error codes is
not feasible because the C++ language tightly binds together
constructor exceptions and constructor failurs so that the two have to
be synonymous; if instead we used an errno-like approach such as

SomeType anObject; //Construct an object
// Test whether construction worked
if( SomeType::Const ructionWasOk() ) {
// ...

then not only is the result ugly and error-prone, but it leads to
misbegotten objects that don't really satisfy their type's
invariants--never mind the race conditions inherent in calls to
SomeType::Const ructionWasOk in multithreaded applications. (See
[Stroustrup00] §E.3.5.)"

BTW, that section in Stroustrup can be found here for free:

http://www.research.att.com/~bs/3rd_safe.pdf

See also this GotW:

http://www.gotw.ca/gotw/066.htm

Cheers! --M

Sep 20 '06 #5
"Phlip" <ph******@yahoo .comwrote:
Daniel T. wrote:
>tr*****@gmail.c om wrote:
>>I have heard differing points of view on whether or not
constructor s should throw. I am working on a library, and I need
to know if it is bad form for a consturctor to throw.

Destructors should never throw. Constructors should throw if they
cannot put the object into a valid state.

And all objects should be ready for unit tests. Unit tests often
require objects in a minimally constructed state, without all their
baggage. So a constructor should not sub-construct everything it
could possibly use, because a unit test will just throw it all away.

This isn't just an optimization issue - lean constructors are a sign
of clean designs, and of "constructi on encapsulation".

So the best constructors, following this guideline, are those that
do the minimum to prevent their next expected method, or their
constructor, to not crash. Set your pointers to NULL and return. No
hard logic, so no exceptions.
Agreed except that IMHO, "their next expected method" should actually
read "any of their methods".

I'm not a big fan of empty shell objects that need reams of
initialization calls before they can be used for their purpose.

--
There are two things that simply cannot be doubted, logic and perception.
Doubt those, and you no longer*have anyone to discuss your doubts with,
nor any ability to discuss them.
Sep 20 '06 #6

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

Similar topics

7
9237
by: Michael Andersson | last post by:
Hi! Does the use of exception handling induce a performance penalty during the execution of non exception handling code? Regards, /Michael
5
1372
by: John | last post by:
Hi, In my years as a VB programmer, I have settled into this pattern of creating collections classes, with an AddNew() method. AddNew() validates the parameters, instantiates the object, adds it to the collection, and returns it. The AddNew() method was used to get around the lack of a constructor in VB classes. Now I was just about to...
9
2647
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions have been asked on clc before so it is probably OK. I am a newbie to C++. BS 3rd edition states: % The throw transfers control to a handler for...
8
3571
by: Shane Groff | last post by:
I know this is a recurring discussion (I've spent the last 3 days reading through threads on the topic), but I feel compelled to start it up again. After reading through the existing threads, I find myself convinced that exceptions are a better mechanism, for example because constructors and operators can't return errors, and code that...
10
1766
by: Brian Folke Seaberg | last post by:
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...
21
4402
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How can we avoid throwing exceptions? If we already have an abject witch was initialized wit _create_ we will be forced to call create in copy...
4
2374
by: KC | last post by:
Greeting all! I have a problem that I'm hoping will be of interest to others here, and maybe a solution will crop up. I appoligize for the message's length. Now, I'm new to C# and .NET, so I am developing an application during my learning phase. Because of this, I'm trying to use as many *features* as is reasonable. Some may be more...
16
2155
by: Einar Høst | last post by:
Hi, I'm getting into the Trace-functionality in .NET, using it to provide some much-needed logging across dlls in the project we're working on. However, being a newbie, I'm wondering if some more experienced loggers can provide me with some ideas as to how to log in a simple yet flexible manner. For instance, I'd like the code to be as...
24
4924
by: usenet | last post by:
I am unable to catch floating exceptions (e.g. divide by 0 or 0/0) using the standard exceptions defined in stdexcept. What is the recommended way to catch such exceptions? Thanks, Song
0
7839
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
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
8338
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...
1
7959
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8216
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...
1
5710
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
5390
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...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2345
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

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.