Exception handling in Lisp, as seen from C++, Part 1

In earlier series of articles, I’ve been talking about Lisp language features as they might appear to a C++ programmer.  I went over the power of Lisp macros, and talked about object-oriented programming in Lisp.

Now, we move on to exception handling, referred to in Lisp as conditions.  In the simplest case, conditions look like C++ exceptions.  The programmer wraps a piece of code in a “handler-case” block, the equivalent of try{} in C++.  Somewhere down the call stack, a function throws the exception, and the stack unwinds, looking for an exception handler at each level.  When it finds one, the unwinding stops, the handler is executed, and code continues after the handler (unless the handler itself throws another exception and the stack unwinding proceeds anew).  That’s what the simple case looks like in Lisp, but that’s not the true story, it’s just a one common programming model for conditions.

So, what really happens?  Well, conditions can be addressed by handlers or by restarts.  When a condition is signaled, the environment in which the code is executing is examined.  If the closest handler is a restart, the appropriate function is invoked.  Crucially, Lisp does not unwind the stack in this instance.  The restart runs as if called as a function from the point where the error occured (but with the restart handler unbound, so it won’t be called recursively if the restart signals the exception again).  The restart can, in fact, fix the error and allow flow to continue after the signal (the equivalent of the C++ throw).

With this available, the programmer can, at one point in the code, decide what to do about conditions signaled within the context.  (S)he can decide to operate on the error and then allow the code to continue from the point where the error was signaled, or cause the code to unwind the stack to a handler, or do nothing, and let the signals be controlled by the enclosing context.  While the code that signals the error generally has to be written with the possibility of restarts in mind, it does provide an interesting way to handle exceptional cases.

I will be providing examples in subsequent posts.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.