22.2 Exceptions Versus assert

I l @ ve RuBoard

When a problem occurs, the assert statement prints out an error message and aborts the program. This error message contains the condition that failed, as well as the file name and line number where the problem occurred. This is very useful to a maintenance programmer, but not that useful to an end user .

assert s can also be compiled out of "production" code by using the -DNDEBUG option.

The assert statement is useful for checking for conditions that should never happen. The purpose of the assert is to abort the program as soon as a problem is detected .

Exceptions, on the other hand, are designed to handle conditions that are rare, but expected to occur. These occasional problems can then be handled by the program in a nice way. For example, if we attempt to push too much information on the stack, the program can simply abort that operation and continue with the next step, instead of aborting the entire program.

In general, if you don't know what to do with the error, check it with an assert . If you think that someone may want to handle it, throw an exception.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net