Creating and catching errors
In a situation where you know a runtime error could occur, you can invoke a specific error yourself by using cause-error
. For example:
m: 10
if n = 0 [ cause-error 'math 'zero-divide [] ]
print m / n
This line generates a *** Math Error: attempt to divide by zero
when n
is 0
. This could be useful when entering a function with an n
parameter that could be0
, and when we want to divide byn
in the function.
Note that it needs the literal words 'math
and 'zero-divide
, describing the error's type and name; the third argument is a parameter block, which can be empty. Instead of cause-error
, you can also encounter make error! [math zero-divide]
or even make error! 400
. They all do the same—generate the error with that name or code.
Note
Only use cause-error
if you want to stop your program displaying the error message.
So to summarize, use try
, if error?
, cause-error
, and the error!
object together for proper error handling in Red.
Note
The catch - throw
phrase is meant for...