Re: is such exception handling approach good?



"ajk" wrote:
it is normally not a good idea to do operations in the
ctor that could
cause an exception. the reason for this is that if an
exception is
ever thrown in your ctor you end up with an invalid
object. therefore
it is better to have some other method to initialize such
with and
handle a failure outside the ctor like bool init() or
something.

I beg to differ. It is exactly the opposite. Splitting
object's construction into two parts introduces unnecessary
and dangerous period when object's state is undetermined.
There is nothing wrong with throwing from constructor. You
won't end up with invalid object. You end up with valid
working object if the constructor succeeds, or no object at
all, otherwise.

Alex


.



Relevant Pages

  • Re: is such exception handling approach good?
    ... There is nothing wrong with throwing from constructor. ... an oracle database in the ctor then what should you do with the object ... It may be a good design, it may not be a good design from user's point ... resource API to free-up the resource on exception. ...
    (microsoft.public.vc.language)
  • Re: Close a form from its constructor ?
    ... Well, in the ctor, it hasn't yet been opened or shown, so there isn't much ... you could through an exception? ... to its caller) from it's constructor? ...
    (microsoft.public.dotnet.framework.windowsforms)
  • Re: is such exception handling approach good?
    ... In constructor, we use try block to wrap the exception throwable code, then ... catch it if there are any exception, cleanup resources and rethrow exception ... handle a failure outside the ctor like bool initor something. ...
    (microsoft.public.vc.language)
  • Re: is such exception handling approach good?
    ... the reason for this is that if an exception is ... ever thrown in your ctor you end up with an invalid object. ... handle a failure outside the ctor like bool initor something. ... class MyClass ...
    (microsoft.public.vc.language)
  • Re: is such exception handling approach good?
    ... the reason for this is that if an exception is ... ever thrown in your ctor you end up with an invalid object. ... handle a failure outside the ctor like bool initor something. ... it can't refer to members http://www.gotw.ca/gotw/066.htm ...
    (microsoft.public.vc.language)