Go to the first, previous, next, last section, table of contents.


Cleanup Forms

It is sometimes necessary to be sure 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 to stop this happening.

Special Form: 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
  (unwind-protect
      (let
          ((temporary-file (open (tmp-file-name) "w")))
        ;; 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 no matter what happens.
    (close temporary-file)))
    => nil


Go to the first, previous, next, last section, table of contents.