g++: Exception handling in constructor

Rob Shearer Rob.Shearer@networkinference.com
Wed Dec 11 05:50:00 GMT 2002


This is the difference between a normal try block and a function try
block.
You can simply enclose all your statements in a normal try block, and
you are free to handle all the exceptions which are thrown. You can then
return with the object in any state you want, which might be
"inconsistent" by your own standards, but C++ has initialized all your
members before the function actually began (with default constructors,
if nothing else), so the object is perfectly fine by the language's
standards.

The difference is that the function try block wraps the *initializers*
as well. C++ does not allow you to have an object with some members
initialized and some not. Function try blocks were developed to deal
with precisely this problem: if some of the members can be constructed
and some not, what can you do? The system is responsible for keeping
track of which have been constructed and which have not, and if
something goes wrong only the ones which have been initialized have
their destructors called.

Read up on it in the standard, and I seem to recall a good introduction
to the subject in an old copy of the C++ User's Journal, if you have
access to those archives.

> -----Original Message-----
> From: Frank Grimm [mailto:fgr@foobar-cpa.de] 
> Sent: 11 December 2002 12:50
> To: Rob Shearer
> Cc: gcc-help@gcc.gnu.org
> Subject: Re: g++: Exception handling in constructor
> 
> 
> On Wed, Dec 11, 2002 at 09:41:21AM -0000, Rob Shearer wrote:
> > 
> > >From the standard:
> > 15.3.16: "The exception being handled is rethrown if 
> control reaches the
> > end of ahandler of the function-try-block of a constructor or
> > destructor."
> > 
> > I don't really see any other choice: the object couldn't be 
> constructed,
> > so you can't just return from the constructor and silently leave the
> > caller with uninitialize memory.
> 
> Thanks for your answer.
> 
> I don't see the point that the exceptions is re-thrown _automatically_
> when it _is_ caught by the constructor...
> Because when the exception gets caught by the constructor
> function-try-block, the object can be set to a more-or-less 
> "proper" state 
> and knows that initialization went wrong, and _maybe_ an exception is
> thrown to the caller to signal a problem, but the caller could also
> check the state later with another function (maybe bool 
> operator!() const). 
> -- 
> Frank Grimm // fgr@foobar-cpa.de
>             // www.foobar-cpa.de
> 



More information about the Gcc-help mailing list