throwing exception from constructor

  • Thread starter Thread starter Sek
  • Start date Start date
S

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
 
As far as i know, It's not a appropriate way to throw exception from a
constructor.
If you can make sure that when exception occured, you should dispose
all resoures, such as, File handler, memory, etc.



Sek 写é“:
 
Sek said:
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.

Yup, that's fine. Several framework types do it. For examples, see
Guid(string), the FileStream constructors, and String(char[], int,
int).

Jon
 
simida said:
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.
If you can make sure that when exception occured, you should dispose
all resoures, such as, File handler, memory, etc.

File handles etc, yes - but memory will automatically be cleaned up by
the garbage collector.

Jon
 
Contructor supposed to handle simple tasks like initialization. If up to the
stage you need to throw exception from contructor I think I would suggest
you to review the code.

chanmm
 
chanmm said:
Contructor supposed to handle simple tasks like initialization. If up to the
stage you need to throw exception from contructor I think I would suggest
you to review the code.

Initialization can quite often suggest throwing exceptions,
particularly based on the parameters. What would you suggest FileStream
should do if it's been asked to open a file for reading and the file
doesn't exist?

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

Leon Lambert
 
I agree with what Lambert wrote. I have always tried to insure that
constructors simply put things into an "initialized" 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.).
 
Leon said:
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.

So how would you implement FileStream? If you don't do anything in the
constructor, it's just saving the exception for later on - where's the
advantage of that? Yes, the object would be in a "safe" state - but
it's useless until it's opened the file, and that's the point at which
you should throw an exception if the file can't be found, IMO.

Jon
 
Brian said:
I agree with what Lambert wrote. I have always tried to insure that
constructors simply put things into an "initialized" 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.).

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.

However, using a Create/Initialize/etc method means that your object
isn't really *usable* when the constructor has returned, which is the
state I like to be in.

It's quite possible that throwing exceptions from constructors is a bad
idea in other environments, but I think it's fine in C#.

Jon
 
chanmm said:
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
 
simida said:
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
 
Leon Lambert said:
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
 
Brian C. Barnes said:
I agree with what Lambert wrote. I have always tried to insure that
constructors simply put things into an "initialized" 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
 
Jon said:
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
 
Barry said:
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 "difficulties". 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
 
Carl said:
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
 
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
 
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.
 
Brian C. Barnes said:
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.
 

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

Back
Top