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 finally block will be executed even though code in the try block has an error that the catch block needs to display.

Syntax

(try
(//Protected code)
catch Exception e1)
(//Catch block)
(finally
//Cleanup code)
try-catch with finally block syntax

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 try block to initiate the exception handling block.
  • Line 5: We try to read a file that does not exist using the slurp method. Because the file does not exist, we handle an error using the catch block.
  • Line 6: We try to print the file read by the slurp method, which won't print.
  • Line 7: We use the 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.
  • Line 8: We use finally to print to the screen even though we catch an error in the catch block.
  • Line 9: We call the func.

Free Resources