How to use the try-catch with multiple catch block in Clojure

What is an exception?

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.

What is exception handling?

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.

Syntax

(try
(//Protected code)
catch Exception e1)
catch Exception e1)
(//Catch block)
Trying catch with multiple catch syntax

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.

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))))
(catch Exception e (println (str "caught exception: " (.getMessage e))))))
(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 to initiate the exception handling block.
  • Line 5: We try to read a file that does not exist using the slurp method. It throws an error which we handle 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 the catch to get any general error. So, no message is printed.
  • Line 9: We call the func.

Free Resources