Sunday, September 5, 2010

DrRacket: a dirt-simple exception handler

Exception-handling in Racket is very powerful - but a little overwhelming to me. Suppose you want to do some very very simple exception handling: try something, but if it fails, return an error-value. The way you do this is by using with-handlers:

(with-handlers ([exn:fail? (lambda (exn) 
put-specified-default-here)])
   try-something-here)

There's a lot of goo here, which can be tidied up with some macrology. I give this simple macro, and a couple of examples below:

(define-syntax catch-errors
  (syntax-rules ()
          ((_ error-value body ...)
           (with-handlers ([exn:fail? (lambda (exn) error-value)])
             body ...))))

(catch-errors "Oops" (/ 1 0)) ; "Oops"
(catch-errors "Oops" (/ 6 3)) ; 2
(catch-errors "Oops" (/ 6 3) (/ 16 2)) ; 8

No comments: