ZetCode

Scheme exceptions

last modified November 24, 2026 Guile 3.0

An exception interrupts the normal flow of a program when something goes wrong: a division by zero, a missing file, a value of the wrong type. The code that detects the problem raises an exception, and the nearest handler that has been installed around it decides what happens next. Without a handler, the program stops with an error message. R7RS defines error, raise, with-exception-handler, and guard; Guile provides them in its own (ice-9 exceptions) module together with exception types and the older catch and throw. The examples run with GNU Guile 3.0.7.

Signalling an error

error raises an exception with a message and any number of additional values, called irritants, that describe the problem. It needs no import.

signal.scm
(define (withdraw balance amount)
  (if (> amount balance)
      (error "Insufficient funds:" amount)
      (- balance amount)))

(display (withdraw 100 30))
(newline)
(display (withdraw 100 300))
(newline)
(display "not reached")
(newline)

The first withdrawal succeeds. The second one asks for more money than the balance holds, and withdraw calls error with the message and the requested amount. No handler is installed, so Guile prints the position of the error call, the procedure it was in, and the message followed by the irritant, and exits with status 1. The last display never runs. The output omits the backtrace.

$ guile signal.scm
70
signal.scm:3:6: In procedure withdraw:
Insufficient funds: 300

Catching errors with guard

guard evaluates a body and catches the exceptions raised inside it. It names the exception and lists clauses in the style of cond: the first clause whose test is true handles the exception, and its value becomes the value of the guard form. In Guile 3.0.7 guard comes from (ice-9 exceptions).

guard.scm
(use-modules (ice-9 exceptions))

(define (withdraw balance amount)
  (if (> amount balance)
      (error "Insufficient funds:" amount)
      (- balance amount)))

(define (try-withdraw balance amount)
  (guard (e ((error? e)
             (display "withdrawal of ")
             (display amount)
             (display " refused")
             (newline)
             balance))
    (withdraw balance amount)))

(display (try-withdraw 100 30))
(newline)
(display (try-withdraw 100 300))
(newline)

(define (safe-car x)
  (guard (e (else 'no-car))
    (car x)))

(display (list (safe-car '(a b)) (safe-car '()) (safe-car 42)))
(newline)

try-withdraw catches the error from withdraw and returns the unchanged balance after a message. error? is true for exceptions created by error and for the errors that Guile raises itself, such as the one from car of an empty list or of a number. An else clause catches every exception, as in safe-car. When the body raises nothing, guard returns the value of the body.

$ guile guard.scm
70
withdrawal of 300 refused
100
(a no-car no-car)

Raising any value

An exception does not have to be an error object. Any value can be raised: a symbol, a string, a list. R7RS calls the procedure raise; in Guile 3.0.7 it is raise-exception. The core binding named raise is unrelated: it sends a POSIX signal to the process and accepts only a signal number, so (raise "bad") fails with Wrong type (expecting exact integer): "bad". The (srfi srfi-34) module provides the R7RS raise.

raise.scm
(use-modules (ice-9 exceptions))

(define (check-age age)
  (cond ((not (integer? age)) (raise-exception 'not-an-integer))
        ((negative? age) (raise-exception (list 'negative age)))
        ((> age 150) (raise-exception "unrealistic age"))
        (else age)))

(define (validate age)
  (guard (e ((symbol? e) (list 'symbol e))
            ((string? e) (list 'string e))
            ((and (pair? e) (eq? (car e) 'negative))
             (list 'below-zero-by (- (cadr e)))))
    (check-age age)))

(for-each (lambda (age)
            (write (validate age))
            (newline))
          '(42 4.5 -3 200))

(define (strict age)
  (guard (e ((string? e) 'rejected))
    (check-age age)))

(display (strict 200))
(newline)
(display (strict 'old))
(newline)

check-age raises a symbol, a list, or a string, depending on the problem. The clauses of guard in validate test the type of the raised value, and the list clause takes the amount out of it. When no clause matches, guard raises the exception again, so it continues to the next handler outside. strict handles only strings, and the symbol raised for 'old reaches the top level, where Guile reports the raised value.

$ guile raise.scm
42
(symbol not-an-integer)
(below-zero-by 3)
(string "unrealistic age")
rejected
ice-9/boot-9.scm:1685:16: In procedure raise-exception:
Throw to key `%exception' with args `(not-an-integer)'.

Error objects

The exceptions created by error and by Guile's own errors carry information that can be read with accessor procedures: exception-message, exception-irritants, exception-kind, which returns a symbol naming the kind of error, and exception-origin, which names the procedure that raised it. R7RS has error-object-message and error-object-irritants for the first two.

objects.scm
(use-modules (ice-9 exceptions))

(define (describe label thunk)
  (display "== ")
  (display label)
  (newline)
  (guard (e ((error? e)
             (display "kind:      ")
             (display (exception-kind e))
             (newline)
             (display "message:   ")
             (display (exception-message e))
             (newline)
             (display "irritants: ")
             (write (exception-irritants e))
             (newline)
             (when (exception-with-origin? e)
               (display "origin:    ")
               (display (exception-origin e))
               (newline))))
    (thunk)))

(describe "no irritants" (lambda () (error "Disk is full")))
(describe "irritants"
          (lambda () (error "Unknown colour:" 'mauve "in palette" 3)))
(define disk "sda1")
(describe "computed message"
          (lambda () (error (string-append "Disk " disk " is full"))))
(describe "car" (lambda () (car '())))
(describe "vector-ref" (lambda () (vector-ref (vector 1 2 3) 7)))
(describe "division" (lambda () (/ 5 0)))

Guile stores error messages as templates in which ~S marks the place of an irritant; its error printer fills them in, as in the output of the first example. A message without irritants comes out as it was written. With irritants, the message ends with one ~S for each of them. When the message is not a literal string, Guile 3.0.7 keeps it among the irritants and the message is only ~A, so a handler that needs the text should not rely on exception-message alone. Built-in errors have their own kinds, such as wrong-type-arg and out-of-range, and an origin. Exact division by zero is reported as numerical-overflow with no irritants.

$ guile objects.scm
== no irritants
kind:      misc-error
message:   Disk is full
irritants: ()
origin:    #f
== irritants
kind:      misc-error
message:   Unknown colour: ~S ~S ~S
irritants: (mauve "in palette" 3)
origin:    #f
== computed message
kind:      misc-error
message:   ~A
irritants: ("Disk sda1 is full")
origin:    #f
== car
kind:      wrong-type-arg
message:   Wrong type argument in position 1 (expecting pair): ~S
irritants: (())
origin:    car
== vector-ref
kind:      out-of-range
message:   Argument 2 out of range: ~S
irritants: (7)
origin:    vector-ref
== division
kind:      numerical-overflow
message:   Numerical overflow
irritants: #f
origin:    /

Exception handlers

guard is built on with-exception-handler, which takes a handler procedure and a thunk. The handler is called with the exception at the point of the raise, while the thunk is still running. For an exception raised by error or raise-exception, the handler must not return: it has to leave with a continuation.

handler.scm
(use-modules (ice-9 exceptions))

(define (risky n)
  (if (odd? n)
      (error "odd input:" n)
      (* n 10)))

(define (run n)
  (call/cc
   (lambda (k)
     (with-exception-handler
      (lambda (e)
        (display "handler: ")
        (write (exception-irritants e))
        (newline)
        (k 'failed))
      (lambda ()
        (risky n))))))

(display (list (run 4) (run 5)))
(newline)

(display (with-exception-handler
          (lambda (e) (list 'unwound e))
          (lambda () (+ 1 (raise-exception 'oops)))
          #:unwind? #t))
(newline)

(display (with-exception-handler
          (lambda (e) 0)
          (lambda () (+ 1 (raise-exception 'oops)))))
(newline)

run captures a continuation k before installing the handler. The handler prints the irritants and escapes through k with the symbol failed. Guile adds the keyword argument #:unwind? #t, which leaves the thunk before the handler runs, so the value of the handler becomes the value of the whole form. In the last call the handler simply returns 0. The exception is not continuable, so Guile raises a new &non-continuable error instead of continuing the addition.

$ guile handler.scm
handler: (5)
(40 failed)
(unwound oops)
ice-9/boot-9.scm:1686:16: In procedure raise-exception:
ERROR:
  1. &non-continuable

Continuable exceptions

raise-continuable raises an exception that the handler may answer. Whatever the handler returns becomes the value of the raise-continuable call, and the computation goes on from there. This lets low-level code ask the code around it how to proceed.

continuable.scm
(use-modules (ice-9 exceptions))

(define (parse-setting line)
  (let ((n (string->number line)))
    (if n
        n
        (raise-continuable (list 'bad-number line)))))

(define (parse-all lines)
  (map parse-setting lines))

(define settings '("80" "x24" "7.5" "" "3"))

(display
 (with-exception-handler
  (lambda (e)
    (display "warning: replacing ")
    (write (cadr e))
    (display " with 0")
    (newline)
    0)
  (lambda ()
    (parse-all settings))))
(newline)

(define (with-default value thunk)
  (with-exception-handler
   (lambda (e) value)
   thunk))

(display (with-default -1 (lambda () (parse-all settings))))
(newline)

(display (with-default 'outer
          (lambda ()
            (list (raise-continuable 'a)
                  (with-default 'inner
                                (lambda () (raise-continuable 'b)))))))
(newline)

parse-setting converts a string to a number. For a string that is not a number, it raises a continuable exception with the offending text and uses the reply of the handler as the result. The first handler prints a warning and replies 0, and the parsing goes on to the end of the list. with-default packages the pattern: the same parser produces -1 for the bad entries under a different handler. Handlers nest: the inner raise-continuable is answered by the inner handler, and the outer one only sees exceptions raised outside of it.

$ guile continuable.scm
warning: replacing "x24" with 0
warning: replacing "" with 0
(80 0 7.5 0 3)
(80 -1 7.5 -1 3)
(outer inner)

Exception types

Larger programs need to tell their own errors apart. Guile's define-exception-type creates a new exception type with a parent type, a constructor, a predicate, and field accessors. An exception is made with make-exception from several parts, for example an instance of the new type and a message.

types.scm
(use-modules (ice-9 exceptions))

(define-exception-type &bank-error &error
  make-bank-error bank-error?
  (account bank-error-account))

(define-exception-type &funds-error &bank-error
  make-funds-error funds-error?
  (missing funds-error-missing))

(define (withdraw account balance amount)
  (cond ((not (positive? amount))
         (raise-exception
          (make-exception (make-bank-error account)
                          (make-exception-with-message "Invalid amount"))))
        ((> amount balance)
         (raise-exception
          (make-exception (make-funds-error account (- amount balance))
                          (make-exception-with-message "Insufficient funds"))))
        (else (- balance amount))))

(define (attempt account balance amount)
  (guard (e ((funds-error? e)
             (list (exception-message e) (bank-error-account e)
                   'missing (funds-error-missing e)))
            ((bank-error? e)
             (list (exception-message e) (bank-error-account e)))
            ((error? e)
             (list 'other-error (exception-kind e))))
    (withdraw account balance amount)))

(for-each (lambda (amount)
            (write (attempt "SK-1001" 250 amount))
            (newline))
          (list 100 400 -5 'ten))

&bank-error is a kind of &error with an account field, and &funds-error is a kind of bank error that also records the missing amount. Because of this hierarchy, the bank-error? predicate is true for funds errors as well, so the more specific clause comes first in guard. Both types are kinds of &error, so error? would catch them too. The message made with make-exception-with-message is plain text, without the templates of error. The last call passes a symbol as the amount, and positive? raises a built-in wrong-type-arg error, which only the last clause matches. A record raised with raise-exception is a portable alternative to exception types.

$ guile types.scm
150
("Insufficient funds" "SK-1001" missing 150)
("Invalid amount" "SK-1001")
(other-error wrong-type-arg)

Cleaning up

When an exception leaves a block of code, the rest of the block does not run. Code that must run in any case, such as closing a file, belongs in the after thunk of dynamic-wind, which runs whenever control leaves the body, including by an exception.

cleanup.scm
(use-modules (ice-9 exceptions))

(define (with-resource name proc)
  (dynamic-wind
   (lambda ()
     (display "open ")
     (display name)
     (newline))
   (lambda () (proc name))
   (lambda ()
     (display "close ")
     (display name)
     (newline))))

(define (process name)
  (when (string=? name "broken.dat")
    (error "Cannot parse file:" name))
  (string-length name))

(define (run name)
  (guard (e ((error? e)
             (display "failed on ")
             (write (exception-irritants e))
             (newline)
             #f))
    (with-resource name process)))

(display (run "data.txt"))
(newline)
(display (run "broken.dat"))
(newline)

with-resource simulates opening and closing a resource around a procedure. Processing broken.dat raises an error. Before the guard in run handles it, the exception passes out of the dynamic-wind, so the resource is closed first and the message comes after it. The handler prints the irritants, which hold the file name.

$ guile cleanup.scm
open data.txt
close data.txt
8
open broken.dat
close broken.dat
failed on ("broken.dat")
#f

catch and throw

Before version 3.0, Guile's main exception mechanism was catch and throw, and much existing code still uses them. throw raises an exception identified by a symbol, the key, together with any arguments. catch takes a key, a thunk, and a handler that receives the key and the arguments; the key #t catches everything.

catch.scm
(use-modules (ice-9 exceptions))

(define (lookup key table)
  (let ((entry (assq key table)))
    (if entry
        (cdr entry)
        (throw 'missing-key key))))

(define table '((red . "#ff0000") (green . "#00ff00")))

(display (catch 'missing-key
           (lambda () (lookup 'blue table))
           (lambda (key . args)
             (list 'caught key args))))
(newline)

(display (catch #t
           (lambda () (vector-ref (vector 1 2) 5))
           (lambda (key . args)
             (list 'caught key))))
(newline)

(display (list (false-if-exception (lookup 'red table))
               (false-if-exception (lookup 'blue table))))
(newline)

(display (guard (e ((eq? (exception-kind e) 'missing-key)
                    (list 'guard-saw (exception-args e))))
           (lookup 'blue table)))
(newline)

(write (catch #t
         (lambda () (error "Bad value:" 42))
         (lambda (key . args)
           (cons key args))))
(newline)

The first catch handles the missing-key throw from lookup. The second catches a built-in error, whose key is the kind seen earlier. false-if-exception evaluates an expression and returns #f if it raises anything. The two mechanisms are connected: guard catches a throw, which shows up with the key as its kind and the arguments in exception-args, and catch catches error. The last line shows the raw arguments of an error: the origin, the message template, the irritants, and extra data.

$ guile catch.scm
(caught missing-key (blue))
(caught out-of-range)
(#ff0000 #f)
(guard-saw (blue))
(misc-error #f "Bad value: ~S" (42) #f)

A safe calculator

The last example evaluates arithmetic expressions written as Scheme lists. The evaluator raises its own exception type for the problems it detects, and the code that runs it reports each error and moves on to the next expression.

calculator.scm
(use-modules (ice-9 exceptions))

(define-exception-type &calc-error &error
  make-calc-error calc-error?
  (culprit calc-error-culprit))

(define (calc-error message culprit)
  (raise-exception
   (make-exception (make-calc-error culprit)
                   (make-exception-with-message message))))

(define operators
  (list (cons '+ +) (cons '- -) (cons '* *)
        (cons '/ (lambda (a b)
                   (if (zero? b)
                       (calc-error "division by zero" a)
                       (/ a b))))))

(define (evaluate expr)
  (cond ((number? expr) expr)
        ((and (pair? expr) (= (length expr) 3))
         (let ((op (assq (car expr) operators)))
           (unless op
             (calc-error "unknown operator" (car expr)))
           ((cdr op) (evaluate (cadr expr)) (evaluate (caddr expr)))))
        (else (calc-error "malformed expression" expr))))

(define (run expr)
  (write expr)
  (display " => ")
  (guard (e ((calc-error? e)
             (display "error: ")
             (display (exception-message e))
             (display ", at ")
             (write (calc-error-culprit e)))
            ((error? e)
             (display "internal error: ")
             (display (exception-kind e))))
    (display (evaluate expr)))
  (newline))

(for-each run
          '((+ 1 2)
            (* (+ 1 2) (- 10 4))
            (/ 7 (- 3 3))
            (^ 2 8)
            (+ 1 2 3)
            (+ x 1)
            (/ (* 2 3) 4)))

calc-error raises a &calc-error that holds a message and the culprit, the part of the input that caused the problem. The division operator checks for zero itself, so the user sees a clear message instead of Guile's numerical-overflow. evaluate accepts numbers and three-element lists with a known operator. run evaluates one expression inside a guard: its own errors are reported with their culprit, and any other error, a bug in the evaluator, is reported by its kind. One bad expression does not stop the rest of the list.

$ guile calculator.scm
(+ 1 2) => 3
(* (+ 1 2) (- 10 4)) => 18
(/ 7 (- 3 3)) => error: division by zero, at 7
(^ 2 8) => error: unknown operator, at ^
(+ 1 2 3) => error: malformed expression, at (+ 1 2 3)
(+ x 1) => error: malformed expression, at x
(/ (* 2 3) 4) => 3/2

Source

Exceptions — GNU Guile Reference Manual

In this article we have signalled errors with error, caught them with guard, raised arbitrary values with raise-exception, read the message, irritants, kind, and origin of error objects, written handlers with with-exception-handler, answered continuable exceptions, defined exception types, cleaned up with dynamic-wind, used Guile's catch and throw, and reported errors in a small calculator. The continuations article explains the escapes that handlers use, and the conditionals article covers the cond clauses that guard imitates.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.