How to use finally in the try-catch exception handling
Exception
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
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
finallyblock will be executed even though code in thetryblock has an error that thecatchblock needs to display.
Syntax
(try(//Protected code)catch Exception e1)(//Catch block)(finally//Cleanup code)
Example
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)
Explanation
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.
- Line 3: We define our function
func.
- Line 4: We use the
tryblock to initiate the exception handling block.
- Line 5: We try to read a file that does not exist using the
slurpmethod. Because the file does not exist, we handle an error using thecatchblock.
- Line 6: We try to print the file read by the
slurpmethod, which won't print.
- Line 7: We use the
catchto get a specific errorjava.io.FileNotFoundExceptionin thetryblock 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.
- Line 8: We use
finallyto print to the screen even though we catch an error in thecatchblock.
- Line 9: We call the
func.