Panic in Clojure

In Clojure, we don’t have a direct equivalent of Go’s panic, but we can use exceptions to achieve similar behavior. We typically use exceptions for unexpected errors or situations we’re not prepared to handle gracefully.

(ns panic-example
  (:require [clojure.java.io :as io]))

(defn main []
  ;; We'll use exceptions throughout this site to check for
  ;; unexpected errors. This is the only program on the
  ;; site designed to throw an exception.
  (throw (Exception. "a problem"))

  ;; A common use of exceptions 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
  ;; throwing an exception if we get an unexpected error when creating a new file.
  (try
    (io/make-parents "/tmp/file")
    (spit "/tmp/file" "")
    (catch Exception e
      (throw e))))

(main)

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

When the first exception in main is thrown, 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 throw.

$ clj -M panic_example.clj
Exception in thread "main" java.lang.Exception: a problem
    at panic_example$main.invokeStatic(panic_example.clj:7)
    at panic_example$main.invoke(panic_example.clj:5)
    at panic_example.core(panic_example.clj:17)

Note that unlike some languages which use exceptions for handling of many errors, in Clojure it is idiomatic to use return values to indicate errors wherever possible, often using constructs like (if-let [result (some-function)] result (throw (Exception. "Error message"))).

In Clojure, we often use the ex-info function to create exceptions with additional data attached, which can be useful for programmatically handling different types of errors.

(throw (ex-info "a problem" {:cause :unexpected-error}))

This allows you to attach structured data to your exceptions, which can be retrieved using ex-data if the exception is caught.