Assertion is used to check whether a condition is met(precondition, postcondition, invariants) and help programmers find holes during debugging phase.
For example,
void f(int *p)
{
assert(p);
p->do();
}
My question is do we need to assume the condition could not be met in release mode and handle the case accordingly?
void f(int *p)
{
assert(p);
if (p)
{
p->do();
}
}
After all, assertion means that the condition it tests should NEVER be false. But if, if we don't check it and it fails, program crashes. Sounds like a dilemma. How do you guys deal with it?
If the assertion fails, the program should crash.
An assertion failing means the programmer made a fundamental mistake in their understanding of how it is possible for the program flow to proceed. This is a development aid, not a production aid. In production, one might handle exceptions, as they "might" occur, whereas assertions should "never" fail.
If you're in the camp that says, "Oh, but what if assertions fail in production? I need to catch them!" then you're missing the point. Ask yourself, in such a case, why aren't you just throwing an exception (or otherwise handling the error)?
Generally speaking, assert is not just a shorthand for "if condition not met, throw exception" (well, sometimes that's the operational semantics, but it's not the denotational semantics). Rather, an assertion failing means the application is in a state the developer does not believe is even possible. Do you really want the code to continue executing in such a case? Clearly (I would say), No.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With