Saturday, 29 September 2012

Simple Error Handling in Lisp

Yup, simple error handling in Lisp. Lisp has a really powerful condition/error handling system (also known as it's condition system). We won't delve into that here. This post was actually inspired by MS Excel (I use MS Excel a lot at work). There's an iferror function that may be used in spreadsheet formulae. It is entered into a cell like so:
=IFERROR(1/0, "failed")
In the above formula, because there is an divide by zero error in the first argument, iferror returns the second argument instead. It's simplicity means it's easy to use and understand.

To replicate this behaviour in Common Lisp is fairly easy. I've included it in MathP. Here's the definition as a macro:
(defmacro iferror (try fallback)
    `(handler-case ,try (error () ,fallback)))
Using it is just as easy as in Excel:
(iferror (/ 1 0) 'failed)
I hope the above code is useful to you; Use it however you want. I accept no responsibility for problems arising from it's use. If you do find it useful, I'd be tickled pink to hear from you.

Do you know of a similar macro? Please leave a comment.

1 comment:

  1. I like the scope statement in D2, which lets you say up front what should happen when the current scope is exited, either normally or due to an exception, or both. Fully implementing it in lisp would involve code walking which I decided to avoid for now in favour of simply introducing a new scope with the macro. Current implementation is in emacs lisp but a port to CL proper should be easy.

    There are examples in the comments at the end, but in this use case its like
    (scope :failure-return 'failed (/ 1 0))