[Insight-users] throwing exception inside constructor

Brad King brad.king at kitware.com
Wed Oct 17 12:48:53 EDT 2007


Niels Dekker wrote:
> 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

This is correct.  Throwing from *destructors* is discouraged, and IMO
should be outright banned by convention.  Throwing from constructors is
the proper thing to do when the object cannot be initialized into a
valid state.  Usually this means some resource could not be allocated.

The question here is whether ITK convention allows allocation of
resources during construction (other than perhaps memory for sub-objects
allocated dynamically).  Since there are no constructor arguments for
objects in the LightObject hierarchy, I think the convention discourages
allocation of resources by constructors.

-Brad


More information about the Insight-users mailing list