Re: throwing exception from constructor
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Tue, 1 Aug 2006 20:58:32 +0100
Brian Gideon <briangideon@xxxxxxxxx> wrote:
Jon wrote:
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.
The FileStream constructor is another example of a poor design choice.
IMHO, opening a file is not a simple operation. There should be an
Open method (either instance or static) that performs this work. Even
after reading the documentation it's still not perfectly clear that the
constructor actually opens the file. But the deed has been done and
throwing exceptions is the only appropriate choice.
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.
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: throwing exception from constructor
- From: Brian Gideon
- Re: throwing exception from constructor
- References:
- throwing exception from constructor
- From: Sek
- Re: throwing exception from constructor
- From: Leon Lambert
- Re: throwing exception from constructor
- From: Jon Skeet [C# MVP]
- Re: throwing exception from constructor
- From: Jon Skeet [C# MVP]
- Re: throwing exception from constructor
- From: Brian Gideon
- throwing exception from constructor
- Prev by Date: Re: throwing exception from constructor
- Next by Date: WebRequest and Threadpools
- Previous by thread: Re: throwing exception from constructor
- Next by thread: Re: throwing exception from constructor
- Index(es):
Relevant Pages
|