An exception can be seen as discontinuation in the normal flow of program execution. It can also be an error that causes a complete disruption in the code execution flow.
Exception handling is to make the program respond appropriately when an error occurs. If an error occurs, it responds with the actual cause of the error and possibly where the error occurred.
In this shot, we'll learn to handle an exception using the try catch
with multiple catch blocks.
(try(//Protected code)catch Exception e1)catch Exception e1)(//Catch block)
The try-catch
is used to check for errors in a code (protected code)
. It is also used to give specific error messages (catch block)
in cases where an error occurs in the try block. Multiple catches are used to catch multiple errors, especially if we are not sure of the possible error the code can throw, so we can catch
both specific errors and general errors.
Let's look at the code below:
(ns clojure.examples.example(:gen-class))(defn func [](try(def string1 (slurp "flap.txt"))(println string1)(catch java.io.FileNotFoundException e (println (str "caught file exception: " (.getMessage e))))(catch Exception e (println (str "caught exception: " (.getMessage e))))))(func)
In the above code:
We try to work with a file that does not exist on the platform and throw an error to explain the try catch
exception handling.
func
.try
to initiate the exception handling block.slurp
method. It throws an error which we handle using the catch
block.slurp
method, which won't print.catch
to get a specific error java.io.FileNotFoundException
in the try
block and output an error message if we get an error. For this example, we have an error, and we use the (.getMessage e)
to get the error message.catch
to get any general error. So, no message is printed.func
.