Exception handling within futures and load-file

clojure

Solution

You don't appear to ever be dereferencing (either with `deref` or `@`) the futures you're producing in your example.

If an exception is thrown within a future, attempting to dereference that future will result in a `java.util.concurrent.ExecutionException` being thrown. This exception will wrap whatever was thrown in the future.

(try
  (future (/ 10 0))
  "done"
  (catch Exception e
    (str "caught " e)))

;=> "done"


(try
  @(future (/ 10 0))
  "done"
  (catch Exception e
    (str "caught " e)))

;=> "caught java.util.concurrent.ExecutionException: java.lang.ArithmeticException: Divide by zero"

Problem

I want my clojure program to have a directory of scripts that it can run - each of these scripts is clojure code that I execute with load-file. This happens within a future so that the script runs in its own thread. The problem is I never see any error messages from the scripts. If the script fails there's no way to know what went wrong. I assume that's because there is no exception handling within the future's thread. I can put exception handling into the script, like below, and it works: ``` ;; script code (try (println (/ 10 0)) (catch Exception e (println "Exception: " (.getMessage e)))) ``` However, I'd rather put the exception handling a level up from that, around the load-file, so that I don't have to have the exception handling in the script itself: ``` (defn handleexes [f] (try (f) (catch Exception e (println "exception: " (.getMessage e))))) (defn start-script-play [name] (println "starting script: " name) (let [f (future (handleexes (load-file (str "./scripts/" name))))] (swap! scripts (fn [s] (assoc s name f))))) ``` So there I'm calling the load-file inside handlexes. this doesn't work - mostly. It DOES work when I run a script that contains its own exception handler though, as above! Without the exception handler in the script, nothing. Wierd. Ok well anyway so my question is what the heck is going on here? - are exceptions indeed not handled in futures? - why aren't exceptions caught when they occur within load-file? - how can I catch exceptions in this situation?

Original source