Exception handling in futures and boot file

I want my clojure program to have a directory of scripts that it can run - each of these scripts is the clojure code that I execute with the download file. This will happen in the future, so the script runs on its own thread.

The problem is that I never see error messages from scripts. If the script fails, there is no way to find out what went wrong. I assume that since there is no exception handling in the future thread. I can put exception handling in a script as shown below and it works:

;; script code (try (println (/ 10 0)) (catch Exception e (println "Exception: " (.getMessage e)))) 

However, I would prefer to apply exception handling from this level around the load file, so I don't need to have 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, I call the load file inside handlexes. it doesn't work - basically. It works when I run a script that contains its own exception handler, though as above! Without an exception handler, nothing in the script. Wierd.

Okay, anyway, so my question is what is happening here?

  • are exceptions that are not handled in futures?
  • Why are not exceptions that occur in the load file possible?
  • How can I catch exceptions in this situation?
+6
source share
1 answer

It seems you never play (with deref or @ ) the futures that you produce in your example.

If an exception occurs in the future, an attempt to dereference this future will result in a java.util.concurrent.ExecutionException being thrown. This exception will wrap everything 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" 
+6
source

Source: https://habr.com/ru/post/943554/


All Articles