如何分配nil而不是异常字符串

时间:2012-04-04 13:53:59

标签: clojure try-catch

我的问题是如何从异常中返回nil而不是 - 在使用slurp的情况下 - 不加载的文件名和异常文本?以下是详细信息。

我希望以下代码返回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 (.getMessage e)))]
            file-data))

以下是现在返回的示例。

bene-cmp.core=> (load-file "src/bene_cmp/core.clj")
#'bene-cmp.core/-main
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)"
bene-cmp.core=> 

我试图避免修改此函数,以便抛出异常,然后让调用者使用try / catch块。

谢谢。

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你只需要改变这个:

(catch Exception e (.getMessage e)))]

到此:

(catch Exception e))]