Title

Exception Handling

Authors

William Clinger, R. Kent Dybvig, Matthew Flatt, and Marc Feeley

Status

This SRFI is currently in withdrawn status. Here is an explanation of each status that a SRFI can hold. To provide input on this SRFI, please send email to srfi-12@nospamsrfi.schemers.org. To subscribe to the list, follow these instructions. You can access previous messages via the mailing list archive.

Abstract

The SRFI defines exception-handling constructs for Scheme, including

This SRFI requires a Scheme implementation to raise an exception whenever an error is to be signaled or whenever the system determines that evaluation cannot proceed in a manner consistent with the semantics of Scheme. However, this SRFI does not define the information to be supplied by an implementation for each possible kind of exception; such a specification is left open for future SRFIs.

Issues

None.

Rationale

The goals of the exception mechanism are To this end, the SRFI defines an exception system whose essence can be implemented with CALL-WITH-CURRENT-CONTINUATION. The SRFI also defines a minimal set of constructs for creating and inspecting condition values, which will allow programmers to at least catch primitive exceptions and log exception messages, and to create new libraries that take advantage of exception handling.

Specification

A Scheme implementation ("the system") raises an exception whenever an error is to be signaled or whenever the system determines that evaluation cannot proceed in a manner consistent with the semantics of Scheme. A program may also explicitly raise an exception.

Whenever the system raises an exception, it invokes the current exception handler with a condition object (encapsulating information about the exception) as its only argument. Any procedure accepting one argument may serve as an exception handler. When a program explicitly raises an exception, it may supply any object to the exception handler.

An exception is either continuable or non-continuable. When the current exception handler is invoked for a continuable exception, the continuation uses the handler's result(s) in an exception-specific way to continue. When an exception handler is invoked for a non-continuable exception, the continuation raises a non-continuable exception indicating that the exception handler returned.

The initial current exception handler is implementation-dependent.

Exception Handlers

(CURRENT-EXCEPTION-HANDLER)   [procedure]

Returns the current exception handler.

(WITH-EXCEPTION-HANDLER handler thunk)   [procedure]

Returns the result(s) of invoking thunk. The handler procedure is installed as the current exception handler in the dynamic context of invoking thunk.

Example:

  (call-with-current-continuation
   (lambda (k)
    (WITH-EXCEPTION-HANDLER (lambda (x) (k '()))
                            (lambda () (car '())))))
  ; = '()

(HANDLE-EXCEPTIONS var handle-expr expr1 expr2 ...)   [syntax]

Evaluates the body expressions expr1, expr2, ... in sequence with an exception handler constructed from var and handle-expr. Assuming no exception is raised, the result(s) of the last body expression is(are) the result(s) of the HANDLE-EXCEPTIONS expression.

The exception handler created by HANDLE-EXCEPTIONS restores the dynamic context (continuation, exception handler, etc.) of the HANDLE-EXCEPTIONS expression, and then evaluates handle-expr with var bound to the value provided to the handler.

Examples:

  (HANDLE-EXCEPTIONS exn
                     (begin
                       (display "Went wrong")
                       (newline))
   (car '()))
  ; displays "Went wrong"

  (HANDLE-EXCEPTIONS exn 
                     (cond
                      ((eq? exn 'one) 1)
                      (else (ABORT exn)))
    (case (random-number)
     [(0) 'zero]
     [(1) (ABORT 'one)]
     [else (ABORT "Something else")]))
  ; = 'zero, 1, or (ABORT "Something else")

The HANDLE-EXCEPTIONS form can be implemented with DEFINE-SYNTAX as shown in the Implementation section of this SRFI.

Raising Exceptions

(ABORT obj)   [procedure]

Raises a non-continuable exception represented by obj. The ABORT procedure can be implemented as follows:

 (define (abort obj)
   ((current-exception-handler) obj)
   (abort (make-property-condition
            'exn
            'message
            "Exception handler returned")))
The ABORT procedure does not ensure that its argument is a condition. If its argument is a condition, ABORT does not ensure that the condition indicates a non-continuable exception.

(SIGNAL obj)   [procedure]

Raises a continuable exception represented by obj. The SIGNAL procedure can be implemented as follows:

 (define (signal exn)
  ((current-exception-handler) exn))
The SIGNAL procedure does not ensure that its argument is a condition. If its argument is a condition, SIGNAL does not ensure that the condition indicates a continuable exception.

Condition Objects

(CONDITION? obj)   [procedure]

Returns #t if obj is a condition, otherwise returns #f. If any of the predicates listed in Section 3.2 of the R5RS is true of obj, then CONDITION? is false of obj.

Rationale: Any Scheme object may be passed to an exception handler. This would cause ambiguity if conditions were not disjoint from all of Scheme's standard types.

(MAKE-PROPERTY-CONDITION kind-key prop-key value ...)   [procedure]

This procedure accepts any even number of arguments after kind-key, which are regarded as a sequence of alternating prop-key and value objects. Each prop-key is regarded as the name of a property, and each value is regarded as the value associated with the key that precedes it. Returns a kind-key condition that associates the given prop-keys with the given values.

(MAKE-COMPOSITE-CONDITION condition ...)   [procedure]

Returns a newly-allocated condition whose components correspond to the the given conditions. A predicate created by CONDITION-PREDICATE returns true for the new condition if and only if it returns true for one or more of its component conditions.

(CONDITION-PREDICATE kind-key)   [procedure]

Returns a predicate that can be called with any object as its argument. Given a condition that was created by MAKE-PROPERTY-CONDITION, the predicate returns #t if and only if kind-key is EQV? to the kind key that was passed to MAKE-PROPERTY-CONDITION. Given a composite condition created with MAKE-COMPOSITE-CONDITION, the predicate returns #t if and only if the predicate returns #t for at least one of its components.

(CONDITION-PROPERTY-ACCESSOR kind-key prop-key)   [procedure]

Returns a procedure that can be called with any condition that satisfies (CONDITION-PREDICATE kind-key). Given a condition that was created by MAKE-PROPERTY-CONDITION and kind-key, the procedure returns the value that is associated with prop-key. Given a composite condition created with MAKE-COMPOSITE-CONDITION, the procedure returns the value that is associated with prop-key in one of the components that satisfies (CONDITION-PREDICATE kind-key).

    (let* ((cs-key (list 'color-scheme))
           (bg-key (list 'background))
           (color-scheme? (condition-predicate cs-key))
           (color-scheme-background 
            (condition-property-accessor cs-key bg-key))
           (condition1 (make-property-condition cs-key bg-key 'green))
           (condition2 (make-property-condition cs-key bg-key 'blue))
           (condition3 (make-composite-condition condition1 condition2)))
      (and (color-scheme? condition1)
           (color-scheme? condition2)
           (color-scheme? condition3)
           (color-scheme-background condition3)))
    ; = 'green or 'blue

Standard Condition Kind and Property

When the system raises an exception, the condition it passes to the exception handler must include the 'exn kind with the 'message property. Thus, if exn is a condition representing a system exception, then
 ((condition-property-accessor 'exn 'message) exn)
extracts the error message from exn. Example:
  (HANDLE-EXCEPTIONS exn 
                     (begin
                       (display "Went wrong: ")
                       (display
                        ((condition-property-accessor 'exn 'message) exn))
                       (newline))
   (car '()))
  ; displays something like "Went wrong: can't take car of nil"

Implementation

This SRFI cannot be fully implemented in R5RS because it requires special support from the system, which must 1) call the current exception handler for any system error, 2) define the initial exception handler, and 3) provide a class of condition values disjoint from other Scheme values. However, the functionality can be roughly implemented as follows for a single-threaded system. (For simplicity, we assume that none of the variables defined below will be redefined by a program.)
 (define *current-exn-handler* ...) ; implementation-dependent

 (define (CURRENT-EXCEPTION-HANDLER)
   *current-exn-handler*)

 (define (WITH-EXCEPTION-HANDLER handler thunk)
   (let ((old #f))
    (dynamic-wind
     (lambda () 
       (set! old *current-exn-handler*)
       (set! *current-exn-handler* handler))
     thunk
     (lambda ()
       (set! *current-exn-handler* old)))))

 (define (ABORT obj)
    ((CURRENT-EXCEPTION-HANDLER) obj)
    (ABORT (make-property-condition
            'exn
            'message
            "Exception handler returned")))

 (define (SIGNAL exn)
  ((CURRENT-EXCEPTION-HANDLER) exn))

 (define-syntax HANDLE-EXCEPTIONS
   (syntax-rules ()
     ((_ var handle-body e1 e2 ...)
      ((call-with-current-continuation
         (lambda (k)
           (with-exception-handler
            (lambda (var)
              (k (lambda () handle-body)))
            (lambda ()
              (call-with-values
               (lambda () e1 e2 ...)
               (lambda args (k (lambda () (apply values args)))))))))))))

 ; The following is an approximate implementation of conditions that uses lists,
 ; instead of a disjoint class of values

 (define (CONDITION? obj)
   ; A condition is represented as a pair where the first value of the
   ; pair is this function. A program could forge conditions, and they're
   ; not disjoint from Scheme pairs.
   (and (pair? obj)
        (eq? CONDITION? (car obj))))

 (define (MAKE-PROPERTY-CONDITION kind-key . prop-vals)
   (cons CONDITION? (list (cons kind-key prop-vals))))

 (define (MAKE-COMPOSITE-CONDITION . conditions)
   (cons CONDITION? (apply append
                           (map cdr conditions))))

 (define (CONDITION-PREDICATE kind-key)
   (lambda (exn)
     (if (CONDITION? exn)
         (assq kind-key (cdr exn))
         #f)))

 (define (CONDITION-PROPERTY-ACCESSOR kind-key prop-key)
   (lambda (exn)
     (let ((p ((CONDITION-PREDICATE kind-key) exn)))
       ; either cadr or cdr could fail; should check arguments for
       ; better error reporting:
       (cadr (memq prop-key (cdr p))))))

More Examples

 (define (try-car v)
  (let ((orig (current-exception-handler)))
    (WITH-EXCEPTION-HANDLER
     (lambda (exn)
       (orig (make-composite-condition
              (make-property-condition
               'not-a-pair
               'value
               v)
              exn)))
     (lambda () (car v)))))

 (try-car '(1))
 ; = 1

 (HANDLE-EXCEPTIONS exn
                    (if ((condition-predicate 'not-a-pair) exn)
                        (begin
                         (display "Not a pair: ")
                         (display
                          ((condition-property-accessor 'not-a-pair 'value) exn))
                         (newline))
                        (ABORT exn))
   (try-car 0))
 ; displays "Not a pair: 0"

Copyright

Copyright (C) William Clinger, R. Kent Dybvig, Matthew Flatt, and Marc Feeley (1999). All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Editor: Dave Mason
Last modified: Sun Jan 28 13:40:27 MET 2007