Skip to content

Instantly share code, notes, and snippets.

@greghendershott
Last active January 20, 2018 15:45
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greghendershott/5223970 to your computer and use it in GitHub Desktop.
Save greghendershott/5223970 to your computer and use it in GitHub Desktop.
Using `with-handlers` to catch exceptions.
#lang racket
;; The way to catch exceptions is `with-handlers`.
;; See http://docs.racket-lang.org/reference/exns.html
;;
;; You specify the type of exception, and a function to handle it. The
;; exception object is passed to the function.
;;
;; For exmaple, we'll catch the "generic" `exn:fail?` with a function
;; that we define in-place using `lambda`:
(with-handlers ([exn:fail? (lambda (exn)
(displayln (exn-message exn))
42)])
(error 'foo "bar")
1)
;; =>
;; foo: bar
;; 42
;; Notice that the result of the entire `with-handlers` expression is
;; 42, not 1.
;; There are a variety of exception struct types, nearly all derived
;; from `exn:fail?`.
;;
;; `with-handlers` can take a list of more than one exception type
;; (and its handler function). They are matched in order:
(with-handlers ([exn:fail:user? (lambda (exn)
(display "User error: ")
(displayln (exn-message exn))
99)]
[exn:fail? (lambda (exn)
(display "Generic exception: ")
(displayln (exn-message exn))
42)])
(raise-user-error 'foo "bar")
1)
;; =>
;; User error: foo: bar
;; 99
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment