Next: , Previous: , Up: Non-Local Exits   [Contents][Index] Cleanup Forms

It is sometimes necessary ensure that a certain form is always evaluated, even when a non-local exit would normally bypass that form. The unwind-protect special form is used in this case.

Macro: unwind-protect body-form cleanup-forms…

The body-form is evaluated, if it exits normally the cleanup-forms are evaluated sequentially then the value which the body-form returned becomes the value of the unwind-protect form. If the body-form exits abnormally though (i.e. a non-local exit happened) the cleanup-forms are evaluated anyway and the non-local exit continues.

One use of this is to ensure that an opened file is always closed, for example,

(catch 'foo
          ((temporary-file (open-file (make-temp-name) 'write)))
        ;; Use temporary-file
        (write temporary-file "A test\n")
        ;; Now force a non-local exit
        (throw 'foo))
    ;; This is the cleanup-form it will always
    ;; be evaluated, despite the throw.
    (close temporary-file)))
    ⇒ ()