Next: , Up: Programmatic Error Handling   [Contents][Index] Catching Exceptions

A common requirement is to be able to show as much useful context as possible when a Scheme program hits an error. The most immediate information about an error is the kind of error that it is – such as “division by zero” – and any parameters that the code which signalled the error chose explicitly to provide. This information originates with the error or raise-exception call (or their C code equivalents, if the error is detected by C code) that signals the error, and is passed automatically to the handler procedure of the innermost applicable exception handler.

Therefore, to catch errors that occur within a chunk of Scheme code, and to intercept basic information about those errors, you need to execute that code inside the dynamic context of a with-exception-handler, or the equivalent in C.

For example, to print out a message and return #f when an error occurs, you might use:

(define (catch-all thunk)
    (lambda (exn)
      (format (current-error-port)
              "Uncaught exception: ~s\n" exn)
    #:unwind? #t))

 (lambda () (error "Not a vegetable: tomato")))
-| Uncaught exception: #<&exception-with-kind-and-args ...>
⇒ #f

See Exceptions, for full details.