[Insight-users] throwing exception inside constructor

Niels Dekker niels-xtk at xs4all.nl
Wed Oct 17 12:28:12 EDT 2007


Luis Ibanez wrote:
> Hi Ziv,
>
> Throwing exceptions from constructors is in general discouraged.

It may be discouraged to throw exceptions from constructors of ITK based 
objects (if you say so), but it certainly isn't discouraged "in 
general".

Bjarne Stroustrup even recommends doing so!  From Bjarne's C++ Style and 
Technique FAQ:  "You should throw an exception from a constructor 
whenever you cannot properly initialize (construct) an object. There is 
no really satisfactory alternative to exiting a constructor by a throw." 
www.research.att.com/~bs/bs_faq2.html#ctor-exceptions

> It is easy to end up with partially constructed objects.

If you want to avoid partially constructed objects, throw an exception 
during construction!

> http://nedbatchelder.com/blog/20041202T070735.html

Hmmm....  It says:  "So the lesson is: try not to throw exceptions from 
constructors, or at least understand that they will destroy the object 
for you.  Updated May 2005: Again, this is not correct. The real lesson 
is that throwing exceptions from constructors is perfectly legal, and 
C++ is precisely engineered to specify exactly what will happen. But you 
may be surprised by what happens...."  The article doesn't sound very 
convincing to me.

Anyway, just my two cents...

Kind regards,
--
Niels Dekker
http://www.xs4all.nl/~nd/dekkerware
Scientific programmer at LKEB, Leiden University Medical Center



More information about the Insight-users mailing list