Error Handling in Programs |
Keystroke: [Ctrl] ' Do not type the words "on error." They do not produce the operator.
x on error y
Evaluates y. If y produces an error, evaluates and returns x. Otherwise returns the results of y. The on error operator is a distinct type of conditional operator, guiding execution only in the event of an error during calculation.
Here, on error is used to avoid dividing by zero; when x is 2, the program evaluates as ∞, rather than returning a singularity.
The left placeholder should contain code that always evaluates properly. You can use on error to return a variable for debugging purposes, perform an alternate calculation, or exit the program and return a custom error message.
x←x*kg on error x + kg
to imply that all inputs x to the function must have quantity mass, and using a unitless value for x results in an error before the function is ever executed.
g(f, x) := (f + x) on error f(x)
You can also return custom errors using if statements and the error function. This function allows you to return a Mathcad-style error tooltip from a program and halts the program before any additional steps are performed.