如何在方案中实现try-catch块? [英] How to implement a try-catch block in scheme?

查看:71
本文介绍了如何在方案中实现try-catch块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用(call-cc)方法在方案中实现try-catch块,但我不确定如何将其用于此.我找不到任何例子.

I'm trying to implement a try-catch block in scheme using (call-cc) method but i'm not sure how it can be used for that. I could not find any example.

找到的示例仅包含错误处理,但是我想做的是:如果发生错误,则计划程序必须向用户提供消息(通过显示示例),而不会挂起程序.

And found examples contains just error-handling but what i want to do is: if an error occurred, the scheme program has to give a message to user (via display for-example) without suspending the program.

有可能吗?

推荐答案

由于您想捕获所有错误,例如 raise raise-continuable 所引发的错误您既需要一个异常处理程序(以处理升高的条件),又需要一个退出连续性(以避免继续使用 try 主体). try 的简单语法为:

Since you want to catch all errors, such as ones raised by both raise and raise-continuable you'd need both an exception handler (to deal with raised conditions) and an exit continuation (to avoid continuing with the try body). Simple syntax for try would be:

(import (rnrs base)            ; define-syntax
        (rnrs exceptions))     ; get `with-exception-handler`

(define-syntax try
  (syntax-rules (catch)
    ((_ body (catch catcher))
     (call-with-current-continuation
      (lambda (exit)
        (with-exception-handler
         (lambda (condition)
           catcher
           (exit condition))
         (lambda () body)))))))

例如,它用作:

> (try (begin (display "one\n")
              (raise 'some-error)
              (display "two\n"))
    (catch (display "error\n")))
one
error
some-error       # the return value.

注意:这是R6RS(和R7RS)方案.

Note: this is R6RS (and R7RS) Scheme.

这篇关于如何在方案中实现try-catch块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆