Throwing and Catching

Although we’ve spent most of this chapter talking about how you can use if and cond and case to control the flow of execution through your code, sometimes the flow of execution reaches out and takes control of its own accord. I’m talking, of course, about exceptions. Exceptions are your program’s way of telling the world that something is very, very wrong:

 user=>​ (/ 0 0)
 
 ArithmeticException Divide by zero clojure.lang.Numbers.divide
 (Numbers.java:158)

By default, an exception will terminate your program immediately. If that’s not what you want, you can include some exception-handling code by wrapping your suspect expression in a try:

 (try
  (publish-book book)
  (catch ArithmeticException e (println ​"Math problem." ...

Get Getting Clojure 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.