Error Handling¶
Error handling in Idio is a derivative of condition handling. Conditions are from Scheme and offer a far richer mechanism for handling various states that might be reached within the program.
The fundamental difference between condition handling in Idio and exception handling common to many programming languages is that the program state is not unwound when a condition is raised meaning the handler has an opportunity to perform some appropriate action and return on behalf of the condition-raising code.
There are a few problems here:
a handler returning a value to a function that has raised an error is rarely the best solution
restarts might be a better solution
the restarts mechanism hasn’t been written (yet)
Trapping Errors¶
Most people are familiar with the try/except mechanism from
Python and in Idio we can constrain ourselves to
that style.
The expression for handling an error is:
trap condition* handler body
Here, condition* is a named condition type or a list of condition types.
handler is a unary function which will be called with the
condition that was raised as an argument. Given how bespoke the
required behaviour is, it will usually be an anonymous function.
body is the expression (scope!) that the handler is valid
for.
The constraint is that the handler should call trap-return when it is done.
Using the canonical “divide by zero” error, here, the condition
type, ^rt-divide-by-zero-error, we can try the following:
./x.idio¶define (reciprocate n) {
printf "1 / %s\n" n
1 / n
}
trap ^rt-divide-by-zero-error (function (c) {
eprintf "caught /0\n"
trap-return c
}) {
reciprocate 1
reciprocate 0
reciprocate 2
}
which, when we run it, gives:
$ IDIOLIB=. idio x
1 / 1
1 / 0
caught /0
which is, more or less, what you would expect.
There are two things of interest:
trapreturned a value, c, the condition it was passed, although, as no-one is using the value returned fromtrap, it is lostif we hadn’t have called
reciprocate 0then we would have runreciprocate 2which would have returned0.5and as that was the last expression in its body then that is whattrapwould have returnedAlbeit, no-one is using the value returned from
trap…
Warning
Returning a value to a function that has raised an error is most likely going to compound the problem.
There is an example in condition handlers.
Last built at 2026-01-04T22:40:01Z+0000 from da47fd3 (dev)