# [racket] try/catch/finally idiom in Racket

Sam Phillips <samdphillips at ...> writes:
>*
*>* Hi All,
*>*
*>* I understand using call-with-exception-handler/with-handlers/etc. to
*>* catch exceptions in a block of code, but I'm at a loss to what the best
*>* way to do a "finally" or cleanup action after a block of code. My
*>* intuition is to use dynamic-wind, but I figure there may be a better way
*>* that I just cannot locate in the manual.
*>*
*>* Is there a way to do this that I just cannot find?
*>*
*>* Cheers,
*>* Sam
*>*
*
Sam
Here's an implementation of the finally idiom.
Each line obtains the current continuation, stores it in 'out', then executes
buggy code implemented as (myerror n)
The handler-expression then invokes the continuation to continue evaluating the
remaining lines.
R./
Zack
define (myerror n)
(raise (exn:fail (format "threw error ~A\n" n) (current-continuation-marks))))
(let ((out #f))
(with-handlers ([exn:fail? (lambda (exn) (printf "~A\n" (exn-message exn))
(out))])
(let/cc k (set! out k) (myerror 1))
(let/cc k (set! out k) (myerror 2))
(let/cc k (set! out k) (myerror 3))
(let/cc k (set! out k) (myerror 4))
(let/cc k (set! out k) (myerror 5))))
output:
threw error 1
threw error 2
threw error 3
threw error 4
threw error 5