An exception can be seen as a 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. In a case where 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 use the finally
block in the try catch
exception handling.
try-catch
The try catch
is used to check for errors in a code (protected code
). It helps to give specific error messages (catch block)
when an error occurs in the try
block, that is, the protected code.
finally
Codes in the finally
block will run irrespective of the block it is. In the try-catch
, the finally
block is used to execute a code block whether or not an error occurs. It can be used to continue the flow of the application after an error occurs when placed in the catch
block.
Note: Codes in the
finally
block will be executed even though code in thetry
block has an error that thecatch
block needs to display.
(try(//Protected code)catch Exception e1)(//Catch block)(finally//Cleanup code)
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))))(finally (println "This line has to run")))(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
block to initiate the exception handling block.slurp
method. Because the file does not exist, we handle an error 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.finally
to print to the screen even though we catch an error in the catch
block.func
.