This chapter is from the book

2.11. Error detection and exceptions

Both C++ and Java support exception-handling facilities. In robust production-quality programs, of course, you’ll want to take full advantage of them. For the examples in this book, however, I chose not to throw or catch exceptions, because the subject matter of this book is entirely independent of the error-handling mechanisms. The subtle complexities of try blocks, catch blocks, exception hierarchies, and throw declarations would have detracted from our focus on numeric objects and would have made the examples harder to grasp.

In the few places where my examples detect errors, I have relied on an old C facility, the assert (p) macro. If the Boolean expression parameter p is true, no action is taken, but if it’s false, execution is terminated. No matter where this occurs in the program, termination is immediate and abrupt, with no draining of output buffers or graceful freeing of resources. For example,

The assert (p) macro is admittedly crude, but it is far preferable to ignoring an error. If a constructor leaves an object in an illegal state, or if a function yields nonsense results, even more serious consequences will surely occur later in the program—consequences that may be very hard to diagnose. Never ignore an error.

On the other hand, object orientation eliminates the need for redundant “paranoid” error-checking. A function that takes a Date parameter, for example, may assume that the Date object is legal and should not validate that the month is between 1 and 12.

Java (since version 1.4) has an assert statement:

assert p;
or
assert p : c;

Here, p is the Boolean expression to be validated and c is an expression whose toString() value is to be displayed in the error message. If p is false, an AssertionError exception is thrown.

Problems and exercises

2.11-1The C library designers could have implemented this facility as an ordinary function:

void assert(bool p)
{if (!p) abort();}

Why did they elect instead to make it a parameterized macro?

2.11-2 In both the C and Java facilities, the Boolean expression p should not generate side effects. Why is this a sensible rule?