O'Reilly logo

Functional Programming: A PragPub Anthology by Michael Swaine

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required