Re: throwing exception from constructor



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
.



Relevant Pages

  • Re: throwing exception from constructor
    ... opening the file - which would naturally involve throwing an exception ... The FileStream constructor is another example of a poor design choice. ... opening a file is not a simple operation. ... Open method that performs this work. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Debuggen von Critical Sections
    ... wird der FileStream nicht mehr freigegeben! ... until myFileStream nil; ... weil im Constructor eine Exception auftrat? ...
    (de.comp.lang.delphi.misc)
  • Re: throwing exception from constructor
    ... viable object. ... opening the file - which would naturally involve throwing an exception ... The FileStream constructor is another example of a poor design choice. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: DbC & Exceptions & Style
    ... exception. ... Different ways the constructor can fail ... to avoid writing code that converts GUI data into objects, ... All domain objects must now provide a default constructor. ...
    (comp.object)
  • Re: Controlled types and exception safety
    ... >> propagate an exception. ... >> For an Adjust invoked as part of an assignment operation, ... But a user-defined constructor is ... a user-defined constructor has just turned on the ...
    (comp.lang.ada)