首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在R6RS模式中抛出和处理异常

如何在R6RS模式中抛出和处理异常
EN

Stack Overflow用户
提问于 2010-03-24 23:26:26
回答 1查看 2.3K关注 0票数 7

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

R6RS guard syntax看起来可能符合要求,但是有没有人可以给我展示一个实际使用它的例子?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-03-25 15:25:58

guard的语义是:

代码语言:javascript
复制
(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来处理异常:

代码语言:javascript
复制
(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)))

测试运行:

代码语言:javascript
复制
> (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中有详细的异常处理示例代码说明。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2508934

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档