Re: throwing exception from constructor
- From: Barry Kelly <barry.j.kelly@xxxxxxxxx>
- Date: Tue, 01 Aug 2006 20:52:42 +0100
"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/
.
- Follow-Ups:
- Re: throwing exception from constructor
- From: adebaene
- Re: throwing exception from constructor
- From: Barry Kelly
- Re: throwing exception from constructor
- References:
- throwing exception from constructor
- From: Sek
- Re: throwing exception from constructor
- From: Leon Lambert
- Re: throwing exception from constructor
- From: Barry Kelly
- Re: throwing exception from constructor
- From: Carl Daniel [VC++ MVP]
- throwing exception from constructor
- Prev by Date: Re: throwing exception from constructor
- Next by Date: Re: throwing exception from constructor
- Previous by thread: Re: throwing exception from constructor
- Next by thread: Re: throwing exception from constructor
- Index(es):
Relevant Pages
|