Clojure’s Try/Catch

I have not found a lot written about Clojure’s Try/Catch, especially examples. If you look at the following function


(defn open-csv-file
"Attempts to open a .csv file and complains if the file is not present."

 [file-name]
  (let [file-data (try
    (slurp file-name)
    (catch Exception e (.getMessage e)))]
   file-data))

This will return something that looks like this, if trying to open test_file.csv


bene-cmp.core=> (def x  (open-csv-file "test_file.csv"))
#'bene-cmp.core/x
bene-cmp.core=> x
"test_file.csv (No such file or directory)"

But let’s assume, I want a quiet exception, having the function return a nil, so the caller can make a decision and inform the user. How about this answer from StackOverflow? Here is the result, and it returns nil.


(defn open-csv-file
"Attempts to open a .csv file and complains if the file is not present."

[file-name]
  (let [file-data (try
                    (slurp file-name)
                    (catch Exception e))]
    file-data))

Please note the change is in the catch phrase.

Advertisements

1 Comment

Filed under Clojure

One response to “Clojure’s Try/Catch

  1. The principle is pretty simple, actually. The return value of a try form is the return value of the body in the case of regular control flow, and the return value of the body of the applicable exception handler in the case of an exception. In your first listing, the body of the exception handler is (.getMessage e), which returns the exception’s error message, so that is the return value of the example call.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s