如何在R6RS Scheme中抛出和处理异常

时间:2010-03-24 15:26:26

标签: exception scheme

在R6RS计划中抛出和捕获异常的标准方法是什么?我正在寻找适用于实现R6RS的任何版本的Scheme(不仅仅是PLT)的语法。

R6RS guard syntax看起来可能适合这个法案,但是有人可以告诉我一个如何实际使用它的例子吗?

1 个答案:

答案 0 :(得分:8)

guard的语义是:

(guard (exception-object
       ((condition-1-to-test-exception-object) (action-to-take)
       ((condition-2-to-test-exception-object) (action-to-take)   
       ((condition-N-to-test-exception-object) (action-to-take)
       (else (action-for-unknown-exception)))

我们在这里没有使用辅助else子句。以下示例模拟典型文件IO操作可能引发的异常。我们安装guard来处理异常:

(define mode 0)

(define (open-file) 
  (if (= mode 1)
      (raise 'file-open-error)
      (display "file opened\n")))

(define (read-file)
  (if (= mode 2)
      (raise 'file-read-error)
      (display "file read\n")))

(define (close-file)
  (if (= mode 3)
      (raise 'file-close-error)
      (display "file closed\n")))

(define (update-mode)
  (if (< mode 3)
      (set! mode (+ mode 1))
      (set! mode 0)))

(define (file-operations)
  (open-file)
  (read-file)
  (close-file)
  (update-mode))

(define (guard-demo)
  (guard (ex 
          ((eq? ex 'file-open-error) 
           (display "error: failed to open file ") 
           (update-mode))
          ((eq? ex 'file-read-error) 
           (display "error: failed to read file ") 
           (update-mode))
          (else (display "Unknown error") (update-mode)))
         (file-operations)))

试运行:

> (guard-demo)
file opened
file read
file closed
> (guard-demo)
error: failed to open file 
> (guard-demo)
file opened
error: failed to read file 
> (guard-demo)
file opened
file read
Unknown error
> (guard-demo)
file opened
file read
file closed

有关R6RS的Chapter 7中的示例代码的异常处理的详细说明。