#Handle Err In Constructr
5 messages in this thread
Please show me a way to handle errors inside a constructor. A constructor does
not return a value. It cannot return a NULL or FALSE to the parent program
that the constructor encounters an error. Therefore, all the constructor can
do is to show an error message. But it cannot tell the parent program to
handle this gracefully.
Any suggestion ?
Thanks in advance !!
KC> Please show me a way to handle errors inside
KC> a constructor. A constructor does not return
KC> a value. It cannot return a NULL or FALSE
KC> to the parent program that the constructor
KC> encounters an error.
About your only choice is to throw an exception. Unfortunately, until VC++ 2.0
is released, Microsoft's "pseudo" exception mechanism — really just Windows'
version of setjmp()/longjmp() calls wrapped in macros — can cause problems of
its own because it doesn't unwind the stack. This means that the destructors
of objects declared on the stack don't get called which can result in memory
leaks (or worse).
gc
Norman, Oklahoma USA
— "Is that a *real* poncho or is that a *Sears* poncho?"
Thanks for telling me the truth that I cannot use throwing an exception to
handle errors in a constructor.
Thanks again.
Kwong-hip,
>Please show me a way to handle errors inside a constructor.
Until VC++ comes out with real exception handling, you have two options.
1. Add a flag to the class' members, and have the ctor set the flag to indicate
success or failure. Then the calling function can check to see if the
construction was successful.
2. Only do safe operations in the ctor, and add an Init function to the class
which must be called by the calling function after the ctor is called. This
function can return a value indicating success or failure.
Michael Meadows
Thanks for mentioning two options in handling errors in a constructor. I guess
I will use the option 1 (set a Error-In_Constructor flag). This option seems
to be compatible with the way my program works.
Thanks for your great tips !!