摆脱未捕获的异常

时间:2014-03-24 14:57:09

标签: scheme racket

我有一个用Racket编写的软件,我想使用一个非常非常简单的异常处理程序:当抛出异常时,处理程序打印出一条消息,应用程序终止。< / p>

我可以在以下玩具示例中重现行为:

(define (body) 
  (begin
    (displayln "First line")
    (error "Some error")
    (displayln "This line is not printed")))

(call-with-exception-handler (lambda (x) (displayln "Exception handler")) body)

此代码的输出为:

First line
Exception handler
uncaught exception: #<void>

我希望它在异常处理程序(即打印displayln的表达式)之后的"Exception handler"表达式之后退出。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

试试这个:

(with-handlers ([exn:fail? (lambda (exn)
                             ; in case you need the error message
                             (displayln (exn-message exn))
                             (displayln "Exception handler"))])
  (displayln "First line")
  (error "Some error")
  (displayln "This line is not printed"))

它会打印:

First line
Some error
Exception handler