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.
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.
(try(//protected code)(catch Exception e1 (//catch block)))
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.
(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)
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.
func
.try
to initiate the exception handling block.Note: The
try
block is where our code will be. Thecatch
block is where we throw the error that occurs in the code encapsulated by thetry
block.
slurp
method. Because the file does not exist, there will be an error which we handle using the catch
block.slurp
method.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.func
.