开发者

How to throw and handle exceptions in R6RS Scheme

开发者 https://www.devze.com 2022-12-23 20:12 出处:网络
What is the standard way to throw and catch excepti开发者_开发问答ons in R6RS Scheme?I\'m looking for syntax that works in any version of Scheme (not just PLT) that implements R6RS.

What is the standard way to throw and catch excepti开发者_开发问答ons in R6RS Scheme? I'm looking for syntax that works in any version of Scheme (not just PLT) that implements R6RS.

R6RS guard syntax looks like it might fit the bill, but can somebody show me an example of how to actually use it?


The semantics of guard is:

(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)))

There is an auxiliary else clause that we do not use here. The following sample simulates exceptions that could be raised by typical file IO operations. We install a guard to handle the exceptions:

(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)))

Test run:

> (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

There is a detailed description of exception handling with example code in Chapter 7 of R6RS.

0

精彩评论

暂无评论...
验证码 换一张
取 消