I tend to add lots of assertions to my C++ code to make debugging easier without affecting the performance of release builds. Now, assert
is a pure C macro designed without C++ mechanisms in mind.
C++ on the other hand defines std::logic_error
, which is meant to be thrown in cases where there is an error in the program's logic (hence the name). Throwing an instance might just be the perfect, more C++ish alternative to assert
.
The problem is that assert
and abort
both terminate the program immediately without calling destructors, therefore skipping the cleanup, whereas throwing an exception manually adds unnecessary runtime costs. One way around this would creating an own assertion macro SAFE_ASSERT
, which works just like the C counterpart, but throws an exception on failure.
I can think of three opinions on this problem:
- Stick to C's assert. Since the program is terminated immediately, it does not matter whether changes are correctly unrolled. Also, using
#define
s in C++ is just as bad. - Throw an exception and catch it in main(). Allowing code to skip destructors in any state of the program is bad practice and must be avoided at all costs, and so are calls to terminate(). If exceptions are thrown, they must be caught.
- Throw an exception and let it terminate the program. An exception terminating a program is okay, and due to
NDEBUG
, this will never happen in a release build. Catching is unnecessary and exposes implementation details of internal code tomain()
.
Is there a definitive answer to this problem? Any professional reference?
Edited: Skipping destructors is, of course, no undefined behaviour.
Best Solution
Assertions are for debugging. The user of your shipped code should never see them. If an assertion is hit, your code needs to be fixed.
CWE-617: Reachable Assertion
Exceptions are for exceptional circumstances. If one is encountered, the user won't be able to do what she wants, but may be able to resume somewhere else.
Error handling is for normal program flow. For instance, if you prompt the user for a number and get something unparsable, that's normal, because user input is not under your control and you must always handle all possible situations as a matter of course. (E.g. loop until you have a valid input, saying "Sorry, try again" in between.)