|
In computer programming, an assertion is a programming language construct which immediately aborts program execution if a certain condition or expression is false (an "assertion failure"). It is used by programmers during development to check for potential errors or bugs. To assist with this, the implementation of assertions in many languages will provide information such as the filename and line number in the source code that triggered the assertion failure.
Assertions are used to verify that the assumptions made by a piece of code are actually valid when the code executes; they can serve to document the state the code expects to find before it runs (a precondition), and the state the code expects to result in when it is finished running (a postcondition).
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.
Assertions are also sometimes placed at points the execution is not supposed to reach. For example, assertions could be placed at the default clause of the switch statement in languages such as C, C++, and Java; cases that are intentionally not handled by the programmer will raise an error and abort the program rather than silently continuing in an erroneous state.
Typically, assertions are only enabled in development versions of a software product — they are rarely included in the released version because checking assertions can often result in significant runtime overhead. In addition, it is considered bad practice to rely upon assertions for handling expected error conditions. This is because assertions rarely allow for graceful error recovery: they terminate the program abruptly, may not release some of the resources used by the program, and usually do not display a helpful error message to the user. Because some versions of the program will include assertions and some will not, it is essential that the presence of assertions does not change the meaning of the program. In other words, assertions ought to be free of side effects. The removal of assertions from production code is almost always done automatically. It usually is done via conditional compilation, for example by using the preprocessor in C or C++ or passing an option the runtime engine like the virtual machine of Java.
Some people, however, object to the removal of assertions by citing an analogy that the execution with assertion in development stage and without it in practice is like practicing swimming in a pool with a lifeguard and then going swimming in the sea without a lifeguard. They add assertions also could help make the program fail-safe.
See also
External links
|