Topic: Error handling in constructors
Author: tgibson@steele.ecte.uswc.uswest.com (Todd A Gibson)
Date: Wed, 7 Sep 1994 15:51:01 GMT Raw View
I have a question regarding error handling inside of constructors. I have
a constructor that needs to do several things in order to construct
successfully (open files, allocate memory, etc.)
Since the constructor doesn't have a return value, is the accepted practice
to create a member function that returns the state of the object?
Then right after construction, invoke this member function to check valid
construction?
--
Todd A. Gibson
tgibson@lookout.ecte.uswc.uswest.com
My opinions, not anyone elses...etc
"You boys playing cards?"
Author: wentz@actor.cs.vt.edu (Brian Wentz)
Date: 7 Sep 1994 21:22:58 GMT Raw View
tgibson@steele.ecte.uswc.uswest.com (Todd A Gibson) writes:
> I have a question regarding error handling inside of constructors. I have
>
> Since the constructor doesn't have a return value, is the accepted practice
> to create a member function that returns the state of the object?
> Then right after construction, invoke this member function to check valid
> construction?
Actually, I'd do it the other way around. Have the ctor do
things you know won't fail, then have an a method, maybe FInit()
that does the things that could fail, and returns a boolean
success or fail value.
The big problem with either was is that there is no compile-time
check you can make to be sure that every user of the object actually
calls you FInit() method, the best you can do is make each method
check to see if the object is initted before doing anything,
but that adds extra stuff to remember, and can be broken by
inheritance if not done correctly. All of this is IMHO a big
reason for having exceptions in the language. If you have a
compiler that supports them, I would definately use them
here, making the ctor throw an exception if it fails to get
created correctly.
--
"Don't say the electric chair's not good enough for king-lazy-bones like
myself. More coffee for me boss, because I'm not as messed up as I want
to be." - TMBG
Brian Wentz wentz@vt.edu