- Mastering Delphi Programming:A Complete Reference Guide
- Primo? Gabrijel?i?
- 166字
- 2021-06-24 12:33:34
Assertions
The Assertions compiler options enables or disables code generation for Assert statements. You can use compiler directives {$ASSERTIONS ON} and {$ASSERTIONS OFF} to turn this option on or off in the code. Short forms of this directive are rather cryptic {$C+} and {$C-}.
Delphi allows us to use runtime checks in the code in a form of Assert statements. Assert will check whether the first parameter evaluates to false and will raise an exception with the (optional) second parameter in an exception message, if that is true.
The following statement will raise an exception if variable i is smaller than zero:
Assert(i >= 0, 'Expecting a positive value here');
If you turn code generation for assertions off, the compiler will just skip such statements and they will not generate any code. You can for example use this to remove assertions from the release code. Even if any argument to Assert contains a function call, this function will not be called when assertions are turned off.