[plt-scheme] finally
Eli Barzilay writes:
> On Dec 19, Doug Orleans wrote:
> > What is the PLT equivalent of Java's "finally"? I think I could write
> > something using dynamic-wind, but is there a more efficient way to do
> > it if you just want to guard exits and not entrances?
>
> You can give dynamic-wind `void' as a first argument.
Well, yes, I knew that, I was just wondering if there was something
more efficient/idiomatic. Anyway, here's my macro:
(define-syntax try
(syntax-rules (finally)
((_ expr catch-clause ... (finally finally-expr ...))
(dynamic-wind void
(lambda () (try expr catch-clause ...))
(lambda () finally-expr ...)))
((_ expr ((exn? exn) catch-expr ...) ...)
(with-handlers ((exn? (lambda (exn) catch-expr ...))
...)
expr))))
> (try (/ 1 0)
((exn:fail? exn)
(printf "caught: ~a~%" (exn-message exn))
0)
(finally (printf "hi~%")))
caught: /: division by zero
hi
0
> (try (/ 1 10)
((exn:fail? exn)
(printf "caught: ~a~%" (exn-message exn))
0)
(finally (printf "hi~%")))
hi
1/10
--dougo at place.org