For example, following the dynamic allocation of memory in a programming language such as C, a pointer may be checked to ensure that it is not null before proceeding. Without such an assertion, a reference may occur later that would cause an error.
Asserts are also sometimes placed at points the execution is not supported to reach. For example, they are placed at the default
clause of the switch
statement in languages such as C, C++, and Java.
Typically, all calls to assert are removed from production code since often using assert calls is considered bad programming practice. The function is primarily of interest to developers during the debugging process. That practice is often criticized using an analogy that it is like practicing swimming in a pool with a lifeguard and then going swimming in the sea without a lifeguard.
Java has supported asserts as a built-in functionality of the language since the release of version 1.4. In languages such as Java that also have built-in support for other types of exception handling, there is no reason to include asserts in production code. For this reason, Java's asserts explicitly support removal at compile time.
Compare with Design by contract