473,772 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

throwing exception from constructor

Sek
Is it appropriate to throw exception from a constructor?

Thats the only way i could think of to denote the failure of
constructor, wherein i am invoking couple of other classes to
initialise the object.

TIA
Sek

Aug 1 '06
40 36116
Barry Kelly <ba***********@ gmail.comwrote:
FBar = Bar.Create;
if doThrow then
throw Exception.Creat e;
I've been programming in too many different languages lately. That
should be:

FBar := Bar.Create;
if doThrow then
raise Exception.Creat e('blah');

-- Barry

--
http://barrkel.blogspot.com/
Aug 2 '06 #31
Jon Skeet [C# MVP] wrote:
Carl Daniel [VC++ MVP] wrote:
>>It's widely done, and there's no reason not to do it in .NET. In
unmanaged C++ there are reasons why it's a bad idea, but they don't
apply to .NET.

Excuse me? Indicating failure from a constructor is one of the
primarly reason that exceptions were added to the C++ language over
a decade ago. It is the proper way to signal failure from a
constructor.

I think I must have heard exaggerated claims of the problems involved.
I believe (after a quick search) that after an exception is thrown in
a
C++ constructor that the destructor is not called, so resources need
to
be cleaned up in that situation. I guess some people have taken that
as
a reason not to throw exceptions at all in C++...
That's correct - the body of the destructor is not run, but the destructors
of all base classes and member variables are run (assuming the exception was
thrown from the body of the constructor). If you use the RAII pattern (as
all modern C++ programmers should), your constructor and destructor bodies
will almost always be empty and throwing an exception from the constructor
will do exactly what you'd want it to do.

-cd
Aug 2 '06 #32

Barry Kelly wrote:
<snip>
>
Consider (implementions inlined, copy constructors / assignment
operators / auto_ptr etc. all ignored, for the sake of exposition):

---8<---
class Foo
{
private:
Bar *m_bar;

public:
Foo(bool doThrow)
{
m_bar = new Bar;
if (doThrow)
throw 0;
}

~Foo()
{
delete m_bar;
}
};
--->8---
I think you're projecting your C# way of thinking onto C++, therefore
doing unwise design choices...

Why is the m_bar member allocated allocated on the heap? Any reason for
that in the 1st place ???? 9 times out of 10, the good solution is as
imple as :

class Foo
{
Bar m_bar; //no need for constructor nor destructor
};

Now, suppose there is a good reason to allocate m_bar on the heap, what
about doing modern C++, eg usig the RAII idiom ??

class Foo
{
std::auto_ptr<B arm_bar; //depending on context,
boost::shared_p tr may be another option

public:
Foo(bool doThrow)
: m_bar(new Bar())
{
if (doThrow)
throw 0;
}
};

Arnaud
MVP - VC

Aug 2 '06 #33
Jon wrote:
Brian Gideon <br*********@ya hoo.comwrote:
Having a FileStream which hasn't opened the file seems pretty odd to me
- and would mean that you'd have extra code in everything which used
it. Having no public constructors, just static methods, would be doable
- but I don't see the advantage. From the client's point of view
there'd still be an exception occurring.

Where's the benefit in making the constructor *not* open the file? I'm
all for constructors only doing a sensible amount of work - but not
when that means that an object isn't actually ready for use until
another particular method has been called.
I realize I'm splitting hairs on this one, but the main advantage IMHO
is better compliance with the guideline. Anything that throws an
IOException can't possibly be a simple operation. If you use the
static factory method approach then you would have an object that's
ready to use in one call with the added benefit that the interface
should be easier to understand for the caller.

I think one advantage of the guideline is that it encourages developers
to put complex operations in methods where 1) they're expected and 2)
that have self describing names. To me anyway, line 2 is an order of
magnitude more clear that the stream is open than line 1.

FileStream stream = new FileStream("foo .txt"); // Line 1
FileStream stream = FileStream.Open ("foo.txt"); // Line 2

I'm not saying that throwing exceptions from a constructor is bad. In
fact the same guidelines say it's acceptable when appropriate. Since
the FileStream does attempt to open a file then throwing an exception
is a logical choice.

Aug 2 '06 #34
ad******@club-internet.fr wrote:
Barry Kelly wrote:
<snip>

Consider (implementions inlined, copy constructors / assignment
operators / auto_ptr etc. all ignored, for the sake of exposition):

---8<---
class Foo
{
private:
Bar *m_bar;

public:
Foo(bool doThrow)
{
m_bar = new Bar;
if (doThrow)
throw 0;
}

~Foo()
{
delete m_bar;
}
};
--->8---

I think you're projecting your C# way of thinking onto C++, therefore
doing unwise design choices...

Why is the m_bar member allocated allocated on the heap?
That's irrelevant. This isn't a program, so there are no design choices.
There are only language features.
Now, suppose there is a good reason to allocate m_bar on the heap, what
about doing modern C++, eg usig the RAII idiom ??
I explicitly mentioned that I was ignoring auto_ptr for the sake of
exposition.

In my view, C++'s destructors along with the RAII pattern are basically
required to be overused in order to hack around a limitation in the
language. The RAII pattern works very well for simple scenarios (and
they should be used in such reusable scenarios), like an owned pointer
or a ref-counted pointer, but not every paired operation between
constructor and destructor is so reusable that it merits a new type.

-- Barry

--
http://barrkel.blogspot.com/
Aug 2 '06 #35
Brian Gideon <br*********@ya hoo.comwrote:
Where's the benefit in making the constructor *not* open the file? I'm
all for constructors only doing a sensible amount of work - but not
when that means that an object isn't actually ready for use until
another particular method has been called.

I realize I'm splitting hairs on this one, but the main advantage IMHO
is better compliance with the guideline. Anything that throws an
IOException can't possibly be a simple operation. If you use the
static factory method approach then you would have an object that's
ready to use in one call with the added benefit that the interface
should be easier to understand for the caller.
To split hairs even further, I regard compliance with guidelines per se
as not being an advantage at all - it's only an advantage to the extent
that the guideline itself makes sense. Clearly I disagree with the
generality of the guideline in this case, so compliance with it is
irrelevant to me.
I think one advantage of the guideline is that it encourages developers
to put complex operations in methods where 1) they're expected and 2)
that have self describing names. To me anyway, line 2 is an order of
magnitude more clear that the stream is open than line 1.
*That* is much more of an argument I can at least understand. I still
disagree with it, largely because opening the stream on construction is
precisely the behaviour I expect, but at least it's a reasonable
argument :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Aug 2 '06 #36

"Barry Kelly" <ba***********@ gmail.coma écrit dans le message de news:
ac************* *************** ****@4ax.com...
ad******@club-internet.fr wrote:
In my view, C++'s destructors along with the RAII pattern are basically
required to be overused in order to hack around a limitation in the
language.
Which limitation? The limitation is rather on the .NET finalizer side IMHO :
since you don't know when they are run, there is almost nothing you can do
inside them!
The RAII pattern works very well for simple scenarios (and
they should be used in such reusable scenarios), like an owned pointer
or a ref-counted pointer, but not every paired operation between
constructor and destructor is so reusable that it merits a new type.
That's why there are generic solutions to the RAII idiom, such as ScopeGuard
(http://www.ddj.com/dept/cpp/184403758)

Arnaud
MVP - VC
Aug 3 '06 #37
"Arnaud Debaene" <ad******@clu b-internet.frwrot e:
"Barry Kelly" <ba***********@ gmail.coma écrit dans le message de news:
ac************* *************** ****@4ax.com...
ad******@club-internet.fr wrote:
In my view, C++'s destructors along with the RAII pattern are basically
required to be overused in order to hack around a limitation in the
language.
Which limitation? The limitation is rather on the .NET finalizer side IMHO :
since you don't know when they are run, there is almost nothing you can do
inside them!
We'll have to agree to disagree - I think it's a limitation of the
language definition, nothing to do with .NET or otherwise, in the
context of "throwing an exception from the constructor".
The RAII pattern works very well for simple scenarios (and
they should be used in such reusable scenarios), like an owned pointer
or a ref-counted pointer, but not every paired operation between
constructor and destructor is so reusable that it merits a new type.

That's why there are generic solutions to the RAII idiom, such as ScopeGuard
(http://www.ddj.com/dept/cpp/184403758)
Yes, more hacks and crutches...

-- Barry

--
http://barrkel.blogspot.com/
Aug 4 '06 #38

"Barry Kelly" <ba***********@ gmail.coma écrit dans le message de news:
gf************* *************** ****@4ax.com...
"Arnaud Debaene" <ad******@clu b-internet.frwrot e:
>"Barry Kelly" <ba***********@ gmail.coma écrit dans le message de news:
ac************* *************** ****@4ax.com...
ad******@club-internet.fr wrote:
In my view, C++'s destructors along with the RAII pattern are basically
required to be overused in order to hack around a limitation in the
language.
Which limitation? The limitation is rather on the .NET finalizer side
IMHO :
since you don't know when they are run, there is almost nothing you can
do
inside them!

We'll have to agree to disagree - I think it's a limitation of the
language definition, nothing to do with .NET or otherwise, in the
context of "throwing an exception from the constructor".
But which limitation are you talking about exactly? That's what I don't
understand...
The RAII pattern works very well for simple scenarios (and
they should be used in such reusable scenarios), like an owned pointer
or a ref-counted pointer, but not every paired operation between
constructor and destructor is so reusable that it merits a new type.

That's why there are generic solutions to the RAII idiom, such as
ScopeGuard
(http://www.ddj.com/dept/cpp/184403758)

Yes, more hacks and crutches...
Huuh? Andrei Alexdandrescu doing "hacks and crutchs" ??? Care to justify
your appreciation?

More seriously, I believe there is a true divergence ni philosophy here :
The C++ approach is "do as little as possible in language itself, and as
much as possible in libraries", whereas your approach (I am not really sure
this is indeed the C# approach) is "put everything in language and compiler
itself, so that there is nothing left to do in libraries". I believe the 1st
approach is more flexible because, first, it makes it much easier to replace
a defective component....

Arnaud
MVP - VC
Aug 4 '06 #39
"Arnaud Debaene" <ad******@clu b-internet.frwrot e:
"Barry Kelly" <ba***********@ gmail.coma écrit dans le message de news:
gf************* *************** ****@4ax.com...
We'll have to agree to disagree - I think it's a limitation of the
language definition, nothing to do with .NET or otherwise, in the
context of "throwing an exception from the constructor".

But which limitation are you talking about exactly? That's what I don't
understand...
Like I said, we'll have to agree to disagree.
More seriously, I believe there is a true divergence ni philosophy here :
The C++ approach is "do as little as possible in language itself, and as
much as possible in libraries",
Nonsense! If that were true, the language would look like LISP! :P
whereas your approach (I am not really sure
this is indeed the C# approach) is "put everything in language and compiler
itself, so that there is nothing left to do in libraries".
That's clearly not true, because there seem to be substantial libraries
packaged with the .NET framework. :) Even the C# basic types are defined
in a library!

You'll have to forgive me, I'm being quite facetious, at the end of a
long day.
I believe the 1st
approach is more flexible because, first, it makes it much easier to replace
a defective component....
Consider std::stack::pop () - C++ is a language in which you can't even
write an exception-safe mutator method which returns a value of a
user-defined type!

I think a programming language should have a carefully selected set of
abstractions and abstraction creation tools that are suitable for the
domain to which it is applied. I think C++ has a set of useful
abstractions and abstraction creation tools, but there are interactions
between some of them that are less than desirable - and that the
resulting sum is somewhat less than the sum of its parts. I think it
would be a better language if it removed some features, and changed some
functionality - but then it would no longer be C++.

-- Barry

--
http://barrkel.blogspot.com/
Aug 4 '06 #40

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

Similar topics

3
3504
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? Is this because there could be an exception thrown when the code creates a std::exception? I would assume that is not the case. However, if I want to create a new exception class, derived from std::exception (say MyException) then how can I...
3
5070
by: Scott Brady Drummonds | last post by:
Hi, all, I've a fairly small piece of code that is causing me problems. I'm using std::string and am building a string of several dozen characters using several of std::string's functions: a blank constructor, operator=, and operator+=. This sequence of function calls causes a crash either at the call to operator+= or when the string object leaves scope (which must be the result of the destructor). Specifically, my Windows-based...
40
13535
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
5
2010
by: KJ | last post by:
This is kind of hard to explain but I have a The controls are created with CreateChildControls(). Now let say I click a button and an error occurs in the control. If I throw it up it goes back to the web form. where do I catch the exception at? Example Webform Composite Control
10
5567
by: mttc | last post by:
I read articles that suggest preventing delete by throwing Exception from RowDeleting Event. I not understand where I can catch this Error?
11
11985
by: mangesh | last post by:
I read , FAQ : 17.4] How should I handle resources if my constructors may throw exceptions? Above faq says that use smart pointer in construcors . Because if exception is thrown from constructor it's destructor is not run .So to avoid memory lekage use smart pointer . But if exception is thrown we can release resources in catch block . So use of smart pointer is not must , we have this secnd option . Am i right ?
0
9621
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10264
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9914
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5355
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4009
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
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.