Working with functions
In this section, we will talk about how to make functions resistant to possible errors.
Error handling
In the previous section, we saw that passing the wrong type of argument to a function causes the program to terminate with an error message. Is there a way to guard functions against wrong types and still let the program continue? We know how to test types with type?
, so we can do that instead. Here is a version of theinc
function that is untyped, but protected against the possibility of n
not being an integer:
inc: func [n][ if not integer? n [ print ["n must be an integer, not a" (type? n)] exit ] n +1 ] inc 9;== 10 inc pi ;== n must be an integer, not a float inc "abc";== n must be an integer, not a string
Instead of the if not type? n
test, we can also make this somewhat more readable:
inc: func [n][
unless integer? n [
print ["n must be an integer, not a " (type? n)]
exit
]
n +1
]
This way, we can protect the start of a function with a number...