KKramsch said:
Most of my programming is in C, so I'm a bit shaky on C++, but my
understanding is that "any C program is a C++ program". Assuming
that this is the case, suppose that a C++ program calls a function
from a library written in C, and that the C code for this function
has an "assert" statement. Is there some way for the calling C++
program to trap the exception that results when the assertion fails?
Thanks!
Karl
You shouldn't catch assertion failures.
Shortly, the idea behind the assert macro is that it checks conditions that
must be valid in the code. In other words, it catches something that CAN NOT
happen. For example, you have a non-NULL pointer to something, you check
that it is non-NULL, only you can call some function with this pointer and
it is vital for this function to receive non-NULL pointer. This function's
author can put assert in the function's code to enforce this condition. If
it is ever false, it must be a bug.
True, you can compile code with NDEBUG defined, and this usually wipes out
assert macro and other debugging stuff. So when you test, you compile
without NDEBUG and have the code that checks itself. When you ship your
code, you compile with NDEBUG and get slightly less secure version (but you
have tested it, haven't you ?), which lacks all these checks, so is much
more efficient.
Some library vendors also put asserts to check conditions that CAN NOT
happen with regular use of the library (but can happen if you don't use it
properly). Microsoft's ATL is an example. If this is the case, the library
is not inherently robust, and you have responsibility to learn the proper
use of the library.
From the other side, exceptions usually serve to detect real errors, i.e.
errors that CAN happen. However unlikely they are, but if they can happen,
assert should not be used to signalize them.
What about your case? You have assertion failures in the C library and you
want to get rid of them? Either this library is improperly used, and you
should then learn how to use it to avoid asserts. Or the library is buggy
itself and you should try to fix it or find a replacement. Good define
NDEBUG and recompile the library and you won't have assertion failures. Bad
this doesn't solve the real problem why this assert was placed there.
Cheers,
Rade