gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:45:15 26 4
gpt4 key购买 nike

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

R6RS guard syntax看起来它可能符合要求,但是有人可以向我展示如何实际使用它的示例吗?

最佳答案

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

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

关于exception - 如何在 R6RS Scheme 中抛出和处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2508934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com