Custom Errors in Racket
Our first example demonstrates how to create custom errors in Racket. We’ll create a custom error type and use it in a function.
#lang racket
(require racket/format)
; Define a custom error structure
(struct arg-error (arg message) #:transparent)
; Define a function that may raise our custom error
(define (f arg)
(if (= arg 42)
(raise (arg-error arg "can't work with it"))
(+ arg 3)))
; Main function
(define (main)
(with-handlers ([arg-error?
(lambda (e)
(printf "Argument: ~a~n" (arg-error-arg e))
(printf "Message: ~a~n" (arg-error-message e)))])
(f 42))
(printf "Trying again with a different argument:~n")
(printf "Result: ~a~n" (f 10)))
(main)
In this example, we define a custom error type using struct
. The arg-error
struct has two fields: arg
and message
.
We then define a function f
that takes an argument. If the argument is 42, it raises our custom arg-error
. Otherwise, it returns the argument plus 3.
In the main
function, we use with-handlers
to catch our custom error. This is similar to a try-catch block in other languages. If an arg-error
is caught, we print its details.
To run this program, save it as custom-errors.rkt
and use the racket
command:
$ racket custom-errors.rkt
Argument: 42
Message: can't work with it
Trying again with a different argument:
Result: 13
This example demonstrates how to create and use custom errors in Racket, providing more detailed error information when exceptions occur.