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/