by pilif · 15y ago · 0 comments
And even if I did: If you consider the faulty main() in the linked article: How would you use assert() there to make sure that result as used after the call to foo() is actually usable? If foo() returns -1 (because any of the calls to divide returned -1) then result is undefined.
int divide (int x, int y)
{
defend (y != 0);
return x / y;
}
Now divide is guaranteed to produce a correct result if it's called with correct data. It's up to the caller to make sure the data is correct, or an assert will happen.Just to finish out the example to show how much cleaner asserting is compared to error handling:
int foo(void)
{
volatile int x = 4, y = 28;
return divide(x, y) + divide(y, x);
}
int main ()
{
return foo();
}
That's not to say that error handling doesn't have its place, but it should only be used for data that you can't anticipate.You only run into trouble with this method if the data verification step is the computationally expensive operation.