7
在R6RS計劃中拋出和捕獲異常的標準方法是什麼?我正在尋找適用於實現R6RS的任何版本的Scheme(而不僅僅是PLT)的語法。如何拋出和處理R6RS中的異常計劃
R6RS guard syntax看起來可能符合法案,但有人可以告訴我一個如何實際使用它的例子嗎?
在R6RS計劃中拋出和捕獲異常的標準方法是什麼?我正在尋找適用於實現R6RS的任何版本的Scheme(而不僅僅是PLT)的語法。如何拋出和處理R6RS中的異常計劃
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
有例外R6RS的Chapter 7與示例代碼處理的詳細說明。
謝謝 - 這正是我一直在尋找的。 – 2010-03-26 16:21:37