Re: throwing exception from constructor

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"Carl Daniel [VC++ MVP]"
<cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx> wrote:

Barry Kelly wrote:
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++.

I'd really like to hear those "difficulties". It's quite normal to throw
exceptions from C++ constructors - it's the one of the main reasons that
exceptions were added to C++.

I know - I mentioned it in a parallel post.

Consider (implementions inlined, copy constructors / assignment
operators / auto_ptr etc. all ignored, for the sake of exposition):

---8<---
class Foo
{
private:
Bar *m_bar;

public:
Foo(bool doThrow)
{
m_bar = new Bar;
if (doThrow)
throw 0;
}

~Foo()
{
delete m_bar;
}
};
--->8---

The same in Delphi:

---8<---
type
Foo = class
private
FBar: Bar;

public
constructor Create(doThrow: Boolean);
// inlined here for exposition, not actually valid Delphi syntax
begin
FBar = Bar.Create;
if doThrow then
throw Exception.Create;
end;

destructor Destroy; override;
begin
FBar.Free; // Free() checks for nil pointer first
end;

end;
--->8---

-- Barry

--
http://barrkel.blogspot.com/
.



Relevant Pages

  • Re: Design Question/Constructor Exceptions?
    ... job of a constructor is to prepare a class to be ready for use, ... Constructors certainly may throw exceptions, ... programmers) that's part of your HoursMinutesSeconds API. ... the form of throwing an IllegalArgumentException: ...
    (comp.lang.java.programmer)
  • Re: Catching exceptions thrown from base class constructors?
    ... Although CPP allows you to throw exceptions from the constructor, ... setter from the constructor and let the setter throw the exception if so ... If the base class one throws the derived class ctor ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Constructors And Exceptions
    ... Throwing exceptions from the constructor means that the ... you could have a private cleanup function called by the destructor as well ... The strength of exceptions is that have to deal with the errors, ...
    (comp.lang.cpp)
  • Re: Question concerning object-oriented programming
    ... inspectof the state fails to verify key assertions, ... Number 1 is done with exceptions mainly because the .NET way of enforcing ... Number 2 and 3 I do with assertions. ... constructor Throws an exception in the latest version anyway. ...
    (comp.programming)
  • Re: Allocators and exceptions
    ... This is what you get when the exception is propagated out of a constructor. ... Without exceptions the only option for handling errors ... Constructors should not propagate exceptions up; ... problem altogether, though. ...
    (comp.lang.ada)