REBOL 3 Docs | Guide | Concepts | Functions | Datatypes | Errors |
TOC < Back Next > | Updated: 3-Aug-2010 Edit History |
Assert that condition is true, else throw an assertion error.
Arguments:
conditions [block!]
Refinements:
/type - Safely check datatypes of variables (words and paths)
See also:
In code, it is common to check conditions that should always be valid or true. For example, a check may be made for a value to be in range or of a given datatype.
Since the conditions are always supposed to be true, it's often not worth the effort to provide a detailed error message or explanation if the condition fails, and often such information would only be meaningful to the programmer, not the end user.
To make it easier to check such conditions, the assert function is provided.
Assert can check "truth" conditions, or with a refinement, it can check datatype validity conditions.
To check truth conditions, the argument of assert is a block of one or more conditions, and each is checked (similar to all) to be true:
num: 10 assert [num > 20] ** Script error: assertion failed for: [num > 20] ** Where: assert ** Near: assert [num > 20]
Note that for compound assertions, the error message will indicate the assertion that failed:
num: 10 age: 20 assert [num > 0 age > 50] ** Script error: assertion failed for: [age > 50] ** Where: assert ** Near: assert [num > 0 age > 50]
Look at the error line closely, and you can tell which one failed.
Note: only the first three elements of the failed assertion will be shown (to help avoid long error lines.)
It is also common to validate datatypes using the /type refinement:
age: "37" name: "Bob" assert/type [age integer! name string!] ** Script error: datatype assertion failed for: age ** Where: assert ** Near: assert/type [age integer! name string!]
It fails because age is actually a string, not an integer.
The assert function is useful for validating value before a section of code that depends on those value:
assert/type [ spec object! body block! spec/size number! spec/name [string! none!] spec/options [block! none!] ]
Note that assert is safe to use on all function datatypes. The functions will not be evaluated as part of the process; therefore, assert is an easy way to prevent function passage in unwanted cases.
TOC < Back Next > | REBOL.com - WIP Wiki | Feedback Admin |