Re: exceptions in constructor
vaclavpich@atlas.cz wrote in news:a86624e5-ceef-4c5c-a369-21f67fb935e4
@d31g2000hsg.googlegroups.com:
Hi
I've a question about constructors and exceptions.
//************************************************************
class CObject
{
public:
// ctor
CObject();
// dtor
~ CObject();
// ... methods
};
CObject::CObject()
{
// 1) if ( FAILED( LoadLibrary(...) )) throw exception1;
// 2) if ( FAILED(CoInitialize( 0 )) throw exception2;
// 3) if ( FAILED( CoCreateInstance(....))) throw exception3;
}
CObject::~CObject()
{
// 1) release COM interface
// 2) CoUninitialize();
// 2) FreeLibrary
}
int main(int avgv, char** argc)
{
try{
CObject* ptrObj = new CObject;
}
catch(exception& exc)
{...}
return 0;
}
//****************************************************************
When an error occurs in constructor there is only one way how to say
that samething wrong happen.You can throw an exception but is then a
pointer to CObject valid ?
ptrObj would not have been assigned anything, and in your code would
immediately go out of scope, and thus can not be used anyway.
(Different question: Why are you attempting to new the object anway?
Why not simply declare it as a local variable and then you don't have to
worry about the memory?)
So can you call detructor ~CObject() to release resources. I mean
this : delete ptrObj;
How? There's no way to use ptrObj in the code shown. There's nothing
for you to delete. It won't be used in the try block since the
exception will cause the execution flow to immediately jump to the catch
block, and within the catch block ptrObj is already out of scope and
thus cannot be used.
Is really constructor good place to attach resources (load library or
to get COM interface) ?
I'm not sure.
Sure, but you'd probably want to wrap those in their own RAII classes so
that in the event of them going out of scope, they will dispose of
themselves properly.
I've seen another way. Constructor and destructor are very simple
methods.
All resources are attached in method Initialize and released in
Uninitialize.
These methods can return error codes.
That would be another way. Depends on how you want to use your class.
With the exception-based method you know that your object is always in a
sane and usable state. With the initializtion-based method, your object
has 3 states to worry about: Uninitialized, Initialized, and
Uninitialized but was previously initialized (This might be the same
state as simply Uninitialized).