How to use the try-catch in Clojure

What is an exception?

An exception can be seen as discontinuation in the normal flow of program execution. An exception can also be seen as an error that causes a complete disruption in the flow of the code execution.

What is exception handling?

Exception handling is making the program respond appropriately when an error occurs. In cases where an error occurs, the program should respond with the actual cause of the error and possibly where the error occurred. We achieve this functionality using the try-catch exception handler.

Syntax

(try
(//protected code)
(catch Exception e1 (//catch block)))
Try and catch syntax

The try-catch allows us to check for errors in code (protected code) and output specific error messages (catch block) when an error arises in the code block.

Example

(ns clojure.examples.example
(:gen-class))
(defn func []
(try
(def string1 (slurp "flap.txt"))
(println string1)
(catch Exception e (println (str "caught exception: " (.getMessage e))))))
(func)

Explanation

In the code above, we try to access a file that does not exist on the platform. This throws an error, which we catch, and then prints an explanatory error message in the try-catch exception handling.

  • Line 3: We define our function, func.
  • Line 4: We use the try to initiate the exception handling block.

Note: The try block is where our code will be. The catch block is where we throw the error that occurs in the code encapsulated by the try block.

  • Line 5: We read a file that does not exist using the slurp method. Because the file does not exist, there will be an error which we handle using the catch block.
  • Line 6: We print the file read by the slurp method.
  • Line 7: We use the catch to collect errors in the try block with the default error message. For this example, we have an error and we use the (.getMessage e) to get the error message. We add further explanation to the error message and print it.
  • Line 8: We call the function func.

Free Resources