473,398 Members | 2,125 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

exceptions in constructor

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 ?
So can you call detructor ~CObject() to release resources. I mean
this : delete ptrObj;

Is really constructor good place to attach resources (load library or
to get COM interface) ?
I'm not sure.

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.

Can anybody explain it to me.
Thanks.
Oct 18 '08 #1
3 2755
On 2008-10-18 18:29, va********@atlas.cz wrote:
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 ?
So can you call detructor ~CObject() to release resources. I mean
this : delete ptrObj;
No, there will be no object, so you can not get a pointer to it. On the
other hand you do not have to worry about destroying it either, it is
all taken care of by new.
Is really constructor good place to attach resources (load library or
to get COM interface) ?
I'm not sure.
The C++ programming RAII idiom relies on the constructor allocating all
the resources needed. You should, however, take care to ensure that you
do not leek resources if the constructor throws by doing some exception
handling inside the constructor too:

CObject::CObject()
{
// LoadLibrary(...), if this throws no harm done

try {
// Allocate(...), if this throws we need to clean up
}
catch(...) {
// Clean up, free allocated memory etc.
throw; // Re-throw the exception
}

try {
// Initialise(...), will require clean up too
}
catch(...) {
// Clean up from initialisation
// Free memory etc
throw; // Re-throw the exception
}
}
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.
This is called two stage initialisation, and many consider it a bad thing.

--
Erik Wikström
Oct 18 '08 #2
I suggest you can read the <<Thinking C++>volume TWO. The First
Chapter has a detail explanation covering your problem including the
exceptions in constructors and "RAII idiom". The book can be downloaded
from
http://mindview.net/Books/TICPP/ThinkingInCPP2e.html
Oct 19 '08 #3
va********@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).
Oct 20 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: John | last post by:
Hi, In my years as a VB programmer, I have settled into this pattern of creating collections classes, with an AddNew() method. AddNew() validates the parameters, instantiates the object, adds...
4
by: Zork | last post by:
Hi, I am trying to stop object creation (in this case ill use a ball as the object) via use of exceptions. In essence, if the ball does not have an owner, I do not want the ball object created....
8
by: Shane Groff | last post by:
I know this is a recurring discussion (I've spent the last 3 days reading through threads on the topic), but I feel compelled to start it up again. After reading through the existing threads, I...
10
by: Brian Folke Seaberg | last post by:
I was recently browsing a couple of C++ books at the local bookstore. One book called throwing exceptions from constructors a "dubious practice." Another book recommended not throwing...
21
by: mihai | last post by:
People say that is a bad technique to throw exception from constructors; and that the solution would be to create a function _create_ to initialize an object. What about copy constructors? How...
4
by: slack_justyb | last post by:
Hello everyone, Recently I was coding a little app at home on my Linux box. I'm using gcc 3.3.4 (well actually g++) to compile my programs. I was compiling a module of the app into object code...
4
by: KC | last post by:
Greeting all! I have a problem that I'm hoping will be of interest to others here, and maybe a solution will crop up. I appoligize for the message's length. Now, I'm new to C# and .NET, so I...
2
by: Zytan | last post by:
I know that WebRequest.GetResponse can throw WebException from internet tutorials. However in the MSDN docs: http://msdn2.microsoft.com/en-us/library/system.net.webrequest.getresponse.aspx It...
5
by: adam.timberlake | last post by:
I've just finished reading the article below which goes into some depth about exceptions. The article was rather lucid and so I understand how to implement it all, the thing I'm having trouble with...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.