A Solution: Conditions

Conditions provide a way to have your cake and eat it too. At some high-level function, you pick a strategy for dealing with the error, and register that strategy as a handler. When the lower-level code hits the error, it can then pick a handler without unwinding the call stack. This gives you more options. In particular, you can choose to cope with the problem and continue.

Let’s say that you are processing some log files that include some garbage lines, and that you are content to skip past these lines. You can use with-handler to execute the code with a handler that will replace bad lines with, for example, a simple nil.

 (defn parse-or-nil [logseq]
  (with-handler
  (vec (map parse-log-entry logseq))
  (handle malformed-log-entry ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.