Unwind Protect

unwind-protect is a special operator in CommonLisp that allows the programmer to ensure that cleanup code is invoked whenever a block of code exits, regardless of how the exit occurs. As Lisp features GarbageCollection (deallocating memory is not a concern), this is primarily useful for files and other system resources which are scarce and not suitable for GC.

Similar features exist in other languages; JavaLanguage and CsharpLanguage both allow "finally" clauses as part of try blocks, which do essentially the same thing. (One can write a try/finally block without any catch clauses if one only wants UnwindProtect semantics and isn't seeking to write exception handlers). CeePlusPlus doesn't have finally, but stack-allocated objects have their destructors automatically invoked whenever the containing stack frame exits--regardless if the exit is a normal or non-local return (return out of an interior block, or an exception being thrown)--see ResourceAcquisitionIsInitialization/ ResourceAllocationIsInitialization. The one exception in C++ is longjmp() being called--this doesn't guarantee destructors being called (see UnwindingTheStack)

Scheme has this too, but it's called DynamicWind? and also handles continuations properly. DynamicWind? lets you specify code that will be executed automatically when control enters or leaves the dynamic extent of the function. So you could specify code to SetUp? the open files or network connections and code to TearDown? them, and whenever control enters or leaves the DynamicWind? block, those are invoked.


EditText of this page (last edited April 14, 2008) or FindPage with title or text search