Re: Assertion vs Exception Handling
On Mar 9, 3:32 am, DT <dongta....@gmail.com> wrote:
1. I have a long array and I want to check element of the array fails
my test, for example:
for (int i ...) {
if (a[i]==0) {
cout << "failed " << i << "\n"; break;
}
}
Define what you mean by "fails". Can the case only occur
because of a programming error? Can it occur because of e.g.
resource limitations (insufficient memory, etc.)? Or as a
result of bad user input?
Plus, I only want to compile this error checking code in the
debug mode.
Why? That doesn't normally make sense.
If I can use assertion, how to do it?
Just
assert(a[i] == 0);
But most of the time, assertions will be active in released
code.
Otherwise, should I use exception handling and how?
Whether exception handling or assertions are more appropriate
depends on the type of error and the application domain. And
possibly other considerations as well.
2. If an assertion fails before the cleanup code (i.e. freeing
the pointers), would I experience memory leak? If so, how to
avoid such problems?
An assertion failure terminates your program brutally, with an
abort. The system will clean up most things correctly. And in
cases justifying an assertion failure, you might not want to
clean up others---having the temporary files can help localize
the error.
--
James Kanze