E
E. Robert Tisdale
garyolsen said:In C++ what kind of unexpected conditions should be handled as exceptions?
None!
An exception is an *expected* but unpredictable [random] event
that cannot be prevented but but must be "handled" at run time.
Programming errors (bugs) are *not* exceptions.
Bugs cause *unexpected* but predicable events once detected
and can only be "handled" by the programmer by fixing the bug.
Fixing the bug prevents the event from ever occurring again.
You can use the 'assert' C preprocessor macro to help detect bugs.
Whenever possible, an exception should be "handled"
at the point where it is detected.
If it cannot be completely handled at the point where it is detected,
the function must pass enough information back to the calling function
to completely handle the exception and recover. This information
is passed back to the calling function in an "exception" object.
When should not use exception, instead, use regular function returns?
A function may "throw" or "return" an exception [object].
A function that "returns" an exception cannot be used
in any expression that does not test the exception.
For example,
double mySqrt(double x, int* pError) {
double y = sqrt(x);
*pError = errno;
return y;
}
int main(int argc, char* argv[]) {
int Error = 0;
const
double x = atof(argv[1]);
const
double y = 3.0 + (mySqrt(x, &Error) + 30.0)/13.0;
return 0;
}
It isn't possible, in this case, to detect an error in mySqrt
before y is initialized with an invalid result.
Besides dividing by 0, bad memory allocation,
what're the most popular exceptions?
Any function that accepts input from the user
that can't easily be checked before passing it to the function
is a good candidate for exception handling.
In the above example, it is better to test for x < 0.0
before attempting to initialize y.
This topic has been discussed extensively
in the comp.lang.c++ newsgroup so it might be a good idea
to consult Google Groups
http://groups.google.com/