在R6RS方案中抛出和捕获异常的标准方法是什么?我正在寻找在实现R6RS的方案的任何版本(不仅仅是PLT)中工作的语法。
R6RS guard syntax看起来可能符合要求,但是有没有人可以给我展示一个实际使用它的例子?
发布于 2010-03-25 15:25:58
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 closedR6RS的Chapter 7中有详细的异常处理示例代码说明。
https://stackoverflow.com/questions/2508934
复制相似问题