Handling Class Construction Errors

S

Steve

Hi Folks,

Sorry for this stupid question, but how do you handle errors during class
construction. In other words, if I have a class that loads a file, and
during loading, an error occurs, how do you deal with this in respect of
releasing the resources that would have been allocated if the load was
successful?

What I am trying to achieve is, if I call my class with new, how do I return
NULL if the construction fails (so I can check for fails). Also, if I call
the class without new, ie 'myclassname myclass(param)', how would you deal
with this in event of failure.

I hope my question is clear, I know what I want to ask, but not sure if I've
asked it properly.

Also, are answers to questions like this in Stroustrup's book?

Thanks for your time,
Steve.
 
M

Mike Wahler

Steve said:
Hi Folks,

Sorry for this stupid question, but how do you handle errors during class
construction.

If your object cannot complete construction, throw an
exception.
In other words, if I have a class that loads a file, and
during loading, an error occurs, how do you deal with this in respect of
releasing the resources that would have been allocated if the load was
successful?

If something 'would have been' allocated, that doesn't mean it *was*.
Nothing need be done.
What I am trying to achieve is, if I call my class with new, how do I return
NULL if the construction fails

You don't. A constructor cannot return a value. Also note that
if operator 'new' fails, it will throw an exception.
(so I can check for fails).

Catch the exception(s).
Also, if I call
the class without new, ie 'myclassname myclass(param)', how would you deal
with this in event of failure.

If the object cannot be constructed, throw an exception.
I hope my question is clear, I know what I want to ask, but not sure if I've
asked it properly.

Also, are answers to questions like this in Stroustrup's book?

Yes.

-Mike
 
J

John Harrison

Mike Wahler said:
If your object cannot complete construction, throw an
exception.

This is normally the best thing to do.

However an alternative is to define an 'error state' for your object and
leave the object in that state if an error occurs.

This is what ifstream does for instance.

ifstream f("file_that_does_not_exist");
if (!f.is_open())
cerr << "could not open file\n";

But like Mike says, throwing an exception is normally the better option. I
guess the likelihood of the error occurring would influence which method you
choose.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,833
Latest member
BettyeMacf

Latest Threads

Top