Last active
January 20, 2018 15:45
-
-
Save greghendershott/5223970 to your computer and use it in GitHub Desktop.
Using `with-handlers` to catch exceptions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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