473,766 Members | 2,026 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 36115
"chanmm" <ch*****@hotmai l.comwrote:
Contructor supposed to handle simple tasks like initialization. If up to the
stage you need to throw exception from contructor
Interesting; the need to flag errors from constructors was one of the
motivations for introducing exceptions into C++, since return value
can't be used.

There's nothing wrong with throwing an exception from a constructor.

-- Barry

--
http://barrkel.blogspot.com/
Aug 1 '06 #11
"simida" <yo**********@g mail.comwrote:
As far as i know, It's not a appropriate way to throw exception from a
constructor.
A constructor should leave an object in a valid state. If the
constructor arguments do not give the right information to leave the
object in a valid state with all its invariants holding, then the
constructor should definitely throw an exception.

-- Barry

--
http://barrkel.blogspot.com/
Aug 1 '06 #12
Leon Lambert <la******@inil. comwrote:
As many have stated it is ok to throw an exception in the constructor.
Having said that i would recommend against it. Over the years i have
found it helped me a lot better to just have constructors put the object
into a safe state. I do work that might throw exceptions in a different
method like Setup. I forget all the pains i had in the past that
eventually brought my to doing things this way because I just do it as a
matter of course now.
I remember it being difficult to throw exceptions correctly in C++
constructors, but C# is not C++, and does not have many of its flaws.

There was never a problem in throwing exceptions in constructors Delphi
either, for a simple reason - Delphi initialized the object's fields to
all-zeros before running the constructor. In Delphi, when a constructor
threw an exception, the destructor was invoked. Because all the fields
were initialized to zero, it was trivial for the destructor to correctly
and safely destroy the partially-constructed object. The same is a lot
harder in C++ when one is doing heap allocation etc. in the constructor.

For similar reasons, in C# there's nothing wrong with throwing in the
constructor, and nor are there any complications or difficulties in the
mode of C++.

-- Barry

--
http://barrkel.blogspot.com/
Aug 1 '06 #13
Brian C. Barnes <bc******@newsg roups.nospamwro te:
I agree with what Lambert wrote. I have always tried to insure that
constructors simply put things into an "initialize d" state. If you have to do
something more involved, and especially anything that might throw an
exception or have other failures, I always put them into a "Create" or "Open"
type of function. Yes, this can lead to other errors (i.e. forgetting to call
the appropriate Create function), but I just like it better because of all
the "magic" constructors that happen behind your back (copy constructors,
etc.).
What magic constructors in C#? I suspect you're projecting C++'s
language flaws on other object-oriented languages :)

-- Barry

--
http://barrkel.blogspot.com/
Aug 1 '06 #14
Jon Skeet [C# MVP] wrote:
simida wrote:
>As far as i know, It's not a appropriate way to throw exception from
a constructor.

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. Used together with
the RAII idiom (resource acquisition is initialization - as manifested in
smart pointers and tools like ScopeGuard), exceptions thrown from within a
constructor are safe and easy to use correctly. The alternative, multi-part
construction (via an "init" function), is an error-prone model than permits
partially constructed objects to exist - something that the .NET designers
felt so strongly about that they ensured that all objects are fully
constructed before the first statement of the constructor runs.

-cd
Aug 1 '06 #15
Barry Kelly wrote:
For similar reasons, in C# there's nothing wrong with throwing in the
constructor, and nor are there any complications or difficulties in
the mode of C++.
I'd really like to hear those "difficulti es". It's quite normal to throw
exceptions from C++ constructors - it's the one of the main reasons that
exceptions were added to C++.

-cd
Aug 1 '06 #16
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++...

Jon

Aug 1 '06 #17
Sek,

There are some good comments here already. The Framework Design
Guidelines book says that it is acceptable to throw exceptions when
appropriate. But, it also recommends keeping constructor operations
simple. Often the only thing a constructor needs to do is capture the
parameters. As a result many constructors should only need to throw on
invalid parameters.

I *usually* avoid long running or complex operations in constructors
anyway because it's not clear to the caller that they're happening. If
it makes more sense to construct an object in conjunction with a
complex operation then I'll use a static factory method where I have
the liberty of giving it a clear name using appropriate verbage. If
you go with this approach (and I'm not suggesting that you do) then
you'd naturally be limiting the circumstances where exceptions are
thrown by constructors.

Brian
Sek wrote:
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 #18
But the whole point of .NET is that it is language egnostic - and the
libraries we write in C# may get used by C++/CLI projects, or other languages
that perhaps can't deal with exceptions in constructors as cleanly as C# can.
Since the author really doesn't know what language environment is being used,
I would tend to stick with the more pessimistic approach of doing as little
as possible in the constructor.
C# doesn't *have* "magic" constructors though. I really don't see the
advantage of forcing the client to make two calls when one would do.
The *only* point I could see is that if you're implementing
IDisposable, you need to make sure that your constructor cleans up
after itself if it throws an exception after acquiring a resource. If
you do that in the Create method, you can assume that the client will
call Dispose appropriately.
Aug 1 '06 #19
Brian C. Barnes <bc******@newsg roups.nospamwro te:
But the whole point of .NET is that it is language egnostic - and the
libraries we write in C# may get used by C++/CLI projects, or other languages
that perhaps can't deal with exceptions in constructors as cleanly as C# can.
Care to cite any examples? Any language which can't cope with
constructors throwing exceptions is in serious trouble when it comes to
using the framework classes.
Since the author really doesn't know what language environment is being used,
I would tend to stick with the more pessimistic approach of doing as little
as possible in the constructor.
My approach is to do what's appropriate in the constructor to create a
viable object. In the case of something like FileStream, that involves
opening the file - which would naturally involve throwing an exception
if the file cannot be opened.

--
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 1 '06 #20

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

Similar topics

3
3502
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
5068
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
13531
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
5
2009
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
5566
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
11984
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
9568
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
10168
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
10008
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...
1
9959
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 most users, this new feature is actually very convenient. If you want to control the update process,...
1
7381
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6651
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5279
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2806
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.