Recover in Lisp

In Lisp, we can handle exceptional situations using the condition system. While it doesn’t have an exact equivalent to Go’s panic and recover, we can achieve similar functionality using handler-case and error.

(defun may-error ()
  (error "a problem"))

(defun main ()
  (handler-case
      (progn
        (may-error)
        (format t "After may-error()~%"))
    (error (condition)
      (format t "Recovered. Error:~%~A~%" condition))))

(main)

In this example, we define two functions:

  1. may-error: This function simply raises an error, similar to the mayPanic function in the original example.

  2. main: This function demonstrates how to handle errors in Lisp.

The handler-case macro in Lisp is used to catch and handle conditions (errors). It’s similar in concept to the deferred function with recover in the original example.

Inside handler-case, we first call may-error. If no error occurs, the code would continue to print “After may-error()”. However, since may-error does raise an error, the execution is transferred to the error handler.

The error handler, (error (condition) ...), catches any error and binds it to the variable condition. It then prints a message indicating that it recovered from the error, along with the error message.

When you run this program, you’ll see output similar to:

Recovered. Error:
a problem

This demonstrates that the error was caught and handled, preventing it from crashing the program, similar to how recover works in the original example.

In Lisp, this error handling mechanism is part of the condition system, which is more flexible and powerful than simple exception handling. It allows for not just catching and handling errors, but also restarting computations or taking other complex actions when exceptional situations occur.