> Hi,
I have a class whose constructor accepts a filename and performs some
actions on it[1].
Some things might go wrong, such as not being the right kind of file, the
file doesn't exist, is read-only, etc...
I guess the only way to report an error inside a constructor is to raise
an exception, but it feels a bit extreme to raise an exception becuase a file
couldn't be found....
IS this the best design? Any comments would be appreciated. O:-)
[1] I don't think it's relevant but in case you're curious, it reads all
the version information on it (product name, comapny name, etc...)
It's a religious issue. You could for instance establish an error state
instead and have the caller test your object for success or failure (let me
know if you need instructions on how to code this). You then do this:
CYourObject YourObject(Whatever);
if (YourObject)
{
// Success
}
else
{
// Failure
}
Of course you're then forced to always check for this and other developers
that might use your class will have to check as well. If not and your class
depends on the file being successfully opened then all other class methods
will have to be robust against failure. That is, they will all have check
the state of the file before processing or otherwise respond accordingly
when something fails because the file was never opened. This can get very
tedious of course (and code-intensive, something you want to avoid if
possible). In any case, your decision also depends on whether a "can't open
file" problem is really a critical error in this class. If it is and your
class really can't proceed without this file (and no separate "Open()"
method exists so the caller can correct the problem and try again) then an
exception is fine. In fact, I would even recommend it (I use them all the
time) and you need not even put a try/catch around it in many cases. You
need only do so in the top-level function only, especially where the
situation is considered a critical error and you need to back out of
everything you're doing. One caveat however. Your class' destructor won't be
called if its constructor throws an exception (standard C++ rule). So make
sure you release any other resources that you normally depend on your
destructor to free (as req'd).