Read and Handle Errors

Find where to fix a source error and use guard to handle an error during execution.

You can use a diagnostic to find the code that needs fixing. For errors raised during execution, use guard to choose a result your program can return.

The file examples below use the native lispex command from Getting Started.

Fix E100 before running the program

Save this complete program as syntax.lspx. The closing parenthesis is missing.

LISPEX
(+ 1 2

Run it.

BASH
lispex run syntax.lspx

The command writes this diagnostic to standard error and exits with status 1. Standard output is empty.

E100 syntax.lspx:1:1 unterminated list (missing `)`)

syntax.lspx:1:1 points to line 1, column 1, where the unfinished list starts. Add the closing parenthesis.

LISPEX
(+ 1 2)

Run the same command again.

BASH
lispex run syntax.lspx
3

The command now writes 3 to standard output and exits with status 0. Neither run creates an output file.

E100 occurs while Lispex reads the source, before guard can run. Repair the source first.

Handle an error during execution

Save this complete program as user-error.lspx.

LISPEX
(guard (e ((error-object? e) (error-object-message e))) (error "bad input"))
BASH
lispex run user-error.lspx
"bad input"

The command exits with status 0, leaves standard error empty, and creates no output file.

  1. error creates an error object containing the message "bad input".
  2. guard catches that object and binds it to e.
  3. error-object? checks the value. The matching clause returns its message.

The whole guard expression returns the string. It does not resume at the failing error call. Inspect error objects with error-object?, error-object-message, and error-object-irritants instead of parsing printed diagnostics.

Decide whether to repair or handle

What happenedWhat to do
Reading or checking a form failed before executionFix the indicated source. A handler has not started yet.
A catchable runtime error occurredFix the operation or use guard to return an appropriate result.
No guard clause matched and there is no elseThe original raised object is raised again for an outer handler.
A resource limit was reachedReduce the work or review the resource profile. guard cannot catch ResourceLimit.
The calling application crashedInvestigate the application failure. It is not converted into a Lispex error object.

Continue from a raised condition

Use with-exception-handler when you need a handler procedure. raise-continuable lets that procedure return a value to the call that raised the condition.

Paste this complete example into the Playground.

LISPEX
(with-exception-handler
  (lambda (e) 10)
  (lambda () (+ 1 (raise-continuable "retry"))))

Result

OUTPUT
11

The handler returns 10, then + adds 1. With raise instead, returning normally from the handler produces E332. Use guard when you want to leave the failing expression and return from the surrounding guard.

Read diagnostic stages · Look up a code · Decision records