Assertions in design by contract: Difference between revisions

No edit summary
Line 297:
2
</pre>
 
=={{header|Nim}}==
Nim provides two kind of assertions: assertions which can be deactivated by compiling without checks and assertions which cannot be deactivated.
 
The first kind takes the form: <code>assert boolean_expression</code> with a default message or <code>assert boolean_expression, message</code> when with want a specific message.
For the second kind, <code>assert</code> is simply replaced with <code>doAssert</code>.
 
Assertions may be used anywhere, either as preconditions, post-conditions or invariants.
 
Here is an example:
 
<lang Nim>import math
 
func isqrt(n: int): int =
assert n >= 0, "argument of “isqrt” cannot be negative"
int(sqrt(n.toFloat))</lang>
 
If the assertion is not true, the program terminates in error with the exception AssertionDefect:
<pre>Error: unhandled exception: test.nim(2, 10) `n >= 0` argument of “isqrt” cannot be negative [AssertionDefect]</pre>
 
Note also that, in this case, rather than using an assertion, we could have simply specified that “n” must be a natural:
 
<lang nim>import math
 
func isqrt(n: Natural): int =
int(sqrt(n.toFloat))</lang>
 
If the argument is negative, we get the following error:
<pre>Error: unhandled exception: value out of range: -1 notin 0 .. 9223372036854775807 [RangeDefect]</pre>
 
=={{header|Perl}}==
Anonymous user