Panic in Racket

#lang racket

(require racket/system)

(define (main)
  ; We'll use error throughout this site to check for
  ; unexpected errors. This is the only program on the
  ; site designed to raise an error.
  (error "a problem")

  ; A common use of error is to abort if a function
  ; returns an error value that we don't know how to
  ; (or want to) handle. Here's an example of
  ; raising an error if we get an unexpected error when creating a new file.
  (with-handlers ([exn:fail? (lambda (exn) (error exn))])
    (call-with-output-file "/tmp/file" (lambda (out) (void)))))

(main)

In Racket, we use error to handle situations that would typically cause a panic in other languages. This is similar to throwing an exception in languages like Java or Python.

Running this program will cause it to raise an error, print an error message, and exit with a non-zero status.

When the first error in main is raised, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first error.

$ racket panic.rkt
a problem

Note that unlike some languages which use exceptions for handling of many errors, in Racket it’s idiomatic to use multiple return values or option types for indicating errors where possible, reserving error for truly exceptional situations.

In this example, we’ve used with-handlers to catch any file system errors that might occur when trying to create the file, and re-raise them as a general error. This is similar to the panic behavior in the original example.

The call-with-output-file function is used to create and open a file for writing. If this operation fails, it will raise an exception which is then caught by our handler and converted into an error.

Remember that in Racket, as in many functional programming languages, it’s often preferable to use pattern matching and option types to handle potential errors, rather than relying on exceptions for control flow.