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.
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
.
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.
This allows you to attach structured data to your exceptions, which can be retrieved using ex-data
if the exception is caught.