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.
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.