try
& catch
and assert
has completely different purposes (at least in my view).
try
and catch
are used to cope with expected error conditions (user supplied a filename that doesn't exist, calling new couldn't allocate memory, user entered invalid input of some sort, etc).
The purpose of assert
is the guarantee that the programmer doesn't make mistakes. Hopefully, when running the code in release, you'd have already covered those alternatives, and know that the code is "good". Typical examples of assert
would be some pointer the user should not supply as NULL
is indeed not NULL
, or a linked list has the expected number of nodes [e.g. you count the number of nodes before remove_node
, and check that the number of nodes is indeed exactly one less].
If you are NOT 100% certain (or at least 98.75% certain or whatever level you decide is "good enough") that you have tested all of your code, then you should not make the release - or if you do, get your quality assurance manager to sign off that "we haven't done enough testing, but we are OK with that".
try
and catch
should only be used for things your program can reliably recover from. Not to catch "programmer wrote stupid code that causes a crash".
Edit to clarify the actual answer:
In other words, yes, you should use assert
for things that you don't expect to ever happen in the code [at least if the programmer is not doing things wrong] - this includes for example checking that the vector inside a vector for a matrix is indeed a square when you expect to have a square matrix, for example, or that pointers are not NULL
[except where you expect them to be - and perhaps even check that they ARE NULL
when they SHOULD be].
You should also use error checking with try
/catch
and throw
when things go wrong that could well happen during the running of the actual program in "real life" - disk full (or read-only), files not existing, not enough memory, things of that sort.